Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
How to use variable tablenames in SP
Message
 
 
To
26/07/2011 10:54:21
General information
Forum:
Microsoft SQL Server
Category:
Stored procedures, Triggers, UDFs
Environment versions
SQL Server:
SQL Server 2008
Application:
Desktop
Miscellaneous
Thread ID:
01519190
Message ID:
01519198
Views:
55
This message has been marked as the solution to the initial question of the thread.
>Hello,
>
>I am writing a stored procedure where the tablename in a select statement can be variable.
>
>In VFP I probably would use name substitution:
>
>lcMyTable = "Users"
>lcUser = "Christian"
>SELECT * FROM (lcMyTable) WHERE Username = lcUser
>
>
>In SQL that approach gives me problems, it either says "Must declare the table variable" or if I used a dynamic SQL Must delcare the scalar variable". I guess there is a simple approach but I just can't figure out what is the right one.

In SQL Server you must use dynamic SQL for this purpose, e.g.
declare @SQL nvarchar(max)

set @SQL  = 'select * from ' + quotename(@TableName) + ' where UserName = @cUser'

execute sp_ExecuteSQL @SQL, N'@cUser varchar(20)', @cUser
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform