1

Long time searcher first time poster.

I am trying to create a dynamic SQL script which concatenates the dynamic part into a string to form the From clause so I can declare the table name only once (in future I will add to this so that I can loop through a whole bunch of tables). However when I run the script I get the error: Incorrect syntax near '+'

DECLARE @SCode varchar(4)
DECLARE @Subcode varchar(4)

SET @SCode = 'Client1'
SET @Subcode = 'A'          
SELECT MAX(dateofchange) AS Maxdate, @SCode + 'Type'.ID 
FROM @SCode + 'Type'

Any help would greatly be appreciated. I'm sure the answer will be simple however I am relatievely new to the SQL game.

thanks, SSMS - 2005

2
  • Which +? remove the @SCode +'Type'.ID and see it it runs Commented Apr 10, 2013 at 18:32
  • It is the + in the From as I stripped the code all the way back to just a simple select top 1 * from and it errors. But thanks for the suggestion. Commented Apr 11, 2013 at 7:45

2 Answers 2

3

Using the answer from Alexander Fedorenko in SQl Server 2005 it gives an error "Cannot assign a default value to a local variable." and then for every variable "Must declare the scalar variable "@dml""

The reason for this is that with 2005 you have to declare the variable and set in like

DECLARE @SCode AS VARCHAR(MAX)
SET @scode ='ID12'

I simplified the example a however the below code is a working example for SSMS 2005

DECLARE @dml  as NVARCHAR(MAX)
DECLARE @SCode AS VARCHAR(MAX)
SET @scode ='ID12'
Set @dml='SELECT ID 
FROM '+ QUOTENAME(+@SCode +'Type')
EXEC sp_executesql @dml

Side Note: Why you can't comment on an answer with a code block is beyond me.

Sign up to request clarification or add additional context in comments.

2 Comments

Very valuable info.Thanks @Richard and +1 in your answer;)
Thanks and now I have enough rep to be able to plus 1 your answer too.
1

Try this dynamic SQL script(option for a SQLServer2008+)

DECLARE @SCode varchar(10) = 'Client1',
        @Subcode varchar(10) = 'A',
        @dml nvarchar(400)
SELECT @dml = 'SELECT MAX(dateofchange) AS Maxdate, ID FROM ' + QUOTENAME( + @SCode + 'Type')
EXEC sp_executesql @dml

1 Comment

Please see my additional answer below for the working code and an explanation as to why these changes need to be made.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.