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 |
itmaster
Starting Member
28 Posts |
Posted - 2014-08-04 : 11:52:12
|
Hi,I am trying to use a variable in a sql statement, but it keeps commng back that "the Must declare the variable '@TbHold'"and it is on top.What I have to do is concatinate a date(moth with a year with the table name). any ideas would be reeally appreciated. Thank youMy code:DECLARE @dt3 varchar(4)DECLARE @dt varchar(2)SET @dt = DATEPART(MONTH, GETDATE()) DECLARE @dt2 varchar (4)SET @dt2 = DATEPART(YEAR, GETDATE()) IF LEN(@dt) < 2BEGIN SET @dt = '0' + @dt ENDSET @dt3 = RIGHT(@dt2,2) + @dtDECLARE @@TbHold varchar(8) Set @TbHold = 'RAP' + @dt3 SELECT RACUST, RAACCT, RADATE, RATIME, RAOPHN, RACITY, RASTAT, RATYPE, RADUR, RATREV, RAREV, RAAUTH, BillName, CASE WHEN RATYPE IN ('8DI','8GI','8I','8X','8D') THEN raauth ELSE RAPHN END AS RAPHN,RADATETIME FROM @TbHold |
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
itmaster
Starting Member
28 Posts |
Posted - 2014-08-04 : 13:08:09
|
Hi,Thanks for the reply and that is a godd articale. Unfortunatly I cannot get a ne database design they are not going to allow that.I thought of using dynamic sql, and while I have done some dynamic sql before, I am not sure how to do this here in the from statement.Would you be able to help with that?Thank you |
|
|
MichaelJSQL
Constraint Violating Yak Guru
252 Posts |
Posted - 2014-08-04 : 13:17:38
|
DECLARE @dt3 varchar(4)DECLARE @dt varchar(2)SET @dt = DATEPART(MONTH, GETDATE()) DECLARE @dt2 varchar (4)SET @dt2 = DATEPART(YEAR, GETDATE()) IF LEN(@dt) < 2BEGIN SET @dt = '0' + @dt ENDSET @dt3 = RIGHT(@dt2,2) + @dtDECLARE @TbHold varchar(8) SET @TbHold = 'RAP' + @dt3 DECLARE @strSQL nvarchar(2000) = 'SELECT RACUST, RAACCT, RADATE, RATIME, RAOPHN, RACITY, RASTAT, RATYPE, RADUR, RATREV, RAREV, RAAUTH, BillName, CASE WHEN RATYPE IN (''8DI'',''8GI'',''8I'',''8X'',''8D'') THEN raauth ELSE RAPHN END AS RAPHN,RADATETIME FROM 'SELECT @strSQL = @strSQL + @TbHoldSELECT @strSQLEXEC Sp_executeSql @strSQLIf you are going to use dynamic sql , just make your code as tight as possible. http://msdn.microsoft.com/en-us/library/ms188001.aspx |
|
|
|
|
|
|
|