vijay kumar
vijay kumar

Reputation: 222

declare variable in a table in SQL

I have a below query that requires help

Declare @DB varchar(3) 
set @DB = 'C01' 
SELECT * FROM SVBNORD+@DB WHERE ORDER_DATE = ''

But I get a message

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '+'.

Can you please help me correct my statement.

Upvotes: 0

Views: 98

Answers (2)

StuartLC
StuartLC

Reputation: 107387

You can't do this in normal sql. You can however build up sql dynamically and execute it, like so:

DECLARE @sql NVARCHAR(MAX);

SET @sql = 
'SELECT * FROM SVBNORD' + @DB + N'WHERE ORDER_DATE = ''''';
EXEC(@sql);

You'll need to double up any single quotes in the query.

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 157126

You should use execute to dynamically call the query:

Declare @DB varchar(3) 
set @DB = 'C01' 

execute ('SELECT * FROM SVBNORD'+@DB+' WHERE ORDER_DATE = '''' ')

Upvotes: 2

Related Questions