Re: Run query based on values in another table



bubbles (bubbles.one@xxxxxxxxxxx) writes:
Newbie transiting from VBA to TSQL, using SQL Server 2005 Enterprise:

Need help to do this:

Open Table_A

WITH TableA
DO UNTIL .EOF
Read value from TableA.ColumnA
Run SQL Statement on TableB based on value
Move to the next record
LOOP
END


How do I do this in TSQL?

It is not unlikely that this is a single SQL statement, but it depends on
what operation you intend do to on TableB. Assuming that the operation
is "Give me the total order sum for each customer", the query in Northwind
is:

SELECT C.CompanyName, SUM(OD.Quantity * OD.UnitPrice)
FROM [Order Details] OD
JOIN Orders O ON OD.OrderID = O.OrderID
JOIN Customers C ON O.CustomerID = C.CustomerID
GROUP BY C.CompanyName

A very important lesson of this is that the mindset in SQL is completely
different from a client language.



--
Erland Sommarskog, SQL Server MVP, esquel@xxxxxxxxxxxxx

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
.



Relevant Pages

  • Re: SQL string problem
    ... clean up your parameters before sending them to SQL. ... > You must "escape" any single quotes when sending SQL statements ... > Just pass your SQL statement through this function when opening your ... >> Here is the full SQL statement that is assigned to the strSQL ...
    (microsoft.public.excel.programming)
  • Re: SQL Statement or Cursor
    ... > Your post seems to ask whether you're better off using a cursor or a sql ... > you can achieve this in a SQL Statement, but I'll offer a caution to you ... SQL Server's tsql doesn't have a rownum ... >> Initial Result Set but lacking Incrementing number. ...
    (microsoft.public.sqlserver.programming)
  • Re: Populating a list -- table structure?
    ... this clears up a lot of issues and jargon with SQL. ... I think I'll have to try to get a query that will take the BKitIDs and the KitIDs and bring that information together. ... Queries (just shows the QBE grid for convenience -- ... and It really helps to use Aliases for tablenames as it makes the SQL statement shorter. ...
    (microsoft.public.access.forms)
  • Re: Emailing a Report
    ... CTRL-G to Goto the debuG window -- look at the SQL statement ... The Sub LoopAgmtsSendEmail is highlighted by the Debugger. ...
    (microsoft.public.access.modulesdaovba)
  • Re: SQL string problem
    ... You must "escape" any single quotes when sending SQL statements directly to ... Just pass your SQL statement through this function when opening your ... > Here is the full SQL statement that is assigned to the strSQL ...
    (microsoft.public.excel.programming)