Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2003-01-27 : 08:19:23
|
| Jeffrey writes "I have the following code:DECLARE @StartTimeStamp as datetimeDECLARE @sqlcmd as varchar(8000)DECLARE @LogTable as varchar(20)DECLARE @PlantID as varchar(20)DECLARE @GroupIdent as varchar(20)set @LogTable = 'LOG_APPLE'set @PlantID = 'RETY'set @GroupIdent = '242'BEGINSET @sqlcmd = 'SET @StartTimeStamp = (SELECT TOP 1 timestampFROM ' + @LogTable + 'WHERE timestamp <(SELECT TPMSummaryProcessTimeFROM tblPRSGroupWHERE PlantID = ''' + @PlantID + ''' AND GroupIdent = ''' + @GroupIdent + ''')ORDER BY timestamp DESC)'SELECT @sqlcmdEXECUTE (@sqlcmd)SELECT @StartTimeStampENDWhen I run it from Query Analyzer, I get the following message on the last SELECT statement:Server: Msg 137, Level 15, State 1, Line 2Must declare the variable '@StartTimeStamp'.If I copy the value of @sqlcmd into Query Analyzer like the following with a DECLARE stament, I get the correct output:DECLARE @StartTimeStamp as datetimeSET @StartTimeStamp = (SELECT TOP 1 timestampFROM LOG_PX90JWHERE timestamp <(SELECT TPMSummaryProcessTimeFROM tblPRSGroupWHERE PlantID = 'USFL' AND GroupIdent = '242')ORDER BY timestamp DESC)SELECT @StartTimeStampThe output I expect to receive is a datetime field. In this case, I got a NULL which is fine: ------------------------------------------------------ NULL(1 row(s) affected)My question is, since the statement I am creating in @sqlcmd is syntactically correct, how do I return the value from that command to @StartTimeStamp via the EXECUTE statement? I have also tried using the sp_executesql stored procedure but still no luck. Any help would be appreciated.P.S. I am forcing the variables to values just for testing purposes. I realize I should not be using "timestamp" as a field name also but I am dealing with legacy databases.Thanks... " |
|
|
ValterBorges
Master Smack Fu Yak Hacker
1429 Posts |
Posted - 2003-01-27 : 08:38:43
|
| Take a look at nr's site under sp_executesql you'll find an example on how to return variables.http://www.nigelrivett.com/ |
 |
|
|
jsmith8858
Dr. Cross Join
7423 Posts |
Posted - 2003-01-27 : 10:26:01
|
| Also consider that you may not need dynamic SQL if there aren't too many different log tables.SELECT * FROM Table1 WHERE @LogTable = 'Table1'UNION ALLSELECT * FROM Table2 WHERE @LogTable = 'Table2'UNION ALL..etc ....Just an idea, if the # of different tables is constant. And if there are dozens or hundreds of tables with the exact same structure, maybe ask yourself "why?" and consider putting them all in 1 big table.- Jeff |
 |
|
|
|
|
|