Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Executing SELECT statement dynamically

Status
Not open for further replies.

ninelgorb

Programmer
Mar 7, 2005
111
0
0
US
I need to execute the following select statement dynamically:

SELECT @RC = count(*)
FROM @sTable
WHERE Calldate = @sCalldate

When I write it like this I get errors..

EXEC ('SELECT ' + @RC + ' = count(*)
FROM ' + @sTable +
' WHERE Calldate = ' + @sCalldate)

IS there any way I can do this to get the count into a variable?

Thanks,
Ninel
 
Create a global temp table and insert the count into that, then select the value from the global temp table after the dynamic SQL has been executed.

Denny
MCSA (2003) / MCDBA (SQL 2000)

--Anything is possible. All it takes is a little research. (Me)
[noevil]
Donate to Katrina relief
 
You do not need to create temp tables for things like this, use sp_executesql instead.

Sample Code
Code:
DECLARE @query nvarchar(200),
        @rc int 
-- declare other variables

SET     @query = N'SELECT @rc = count(*) FROM ' + @sTable + ' WHERE Calldate = ' + @sCalldate

EXEC    sp_executesql @query, N'@rc int OUTPUT', @rc OUTPUT

PRINT   'Count is ' + convert(varchar, @rc)

Regards,
AA
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top