Hello,
Wondering why the following won't work:
DECLARE @objName VARCHAR(50)
SET @objName = 'happyhippytable'
set @objCnt "select count(*) from " + @objName + " where begtime > endtime "
or
set @objCnt ("select count(*) from " + @objName + " where begtime > endtime ")
or
set @objCnt = ("select count(*) from " + @objName + " where begtime > endtime ")
or
set @objCnt = exec( "select count(*) from " + @objName + " where begtime > endtime ")
or
set @objCnt = exec( 'select count(*) from ' + @objName + ' where begtime > endtime ')
(Yes, I've tried a number of version:)

Trying to SET a variable from a SELECT
wsr429
I appreciate your reply:)
I have however scoured that sight BEFORE having posted here and it didn't offer me the goods (imagine peeps actually search for an answer 1st... Simply amazing:)
Problem with the static approach is that I'm actually iterating though a bunch of tables that have a known field and what I'm trying to do is generate a dynamic list of SQL statements that can later be passed on to support personnel.
I want to look into all tables that have field X and Y then perform a test on the table with the dynamic SQL and if conditions are met, want to print the SQL.
I did also try sp_executesql but didn't seem to get anywhere with it but will try again.
I'll forward the snippet tomorrow @ work... Thanks again for the reply!
nibs
--
Hugo Kornelis, SQL Server MVP
grooveBiscuit
DECLARE @OBJNAME VARCHAR(50)
DECLARE @SQLSTRING NVARCHAR(4000)
DECLARE @COUNT INT
DECLARE @PARAMS NVARCHAR(100)
SET @OBJNAME = N'TABLENAME'
SET @SQLSTRING = N'SELECT @COUNT = COUNT(*) FROM ' + @OBJNAME
SET @PARAMS = N'@COUNT INT OUTPUT'
EXECUTE SP_EXECUTESQL @SQLSTRING, @PARAMS, @COUNT OUTPUT
SELECT @COUNT
Theres an example in BOL for sql2005 if you search for sp_executesql and look at the parementerized example showing out parameters
Hope that helps