patternsqlModerate
Passing in the table into a stored procedure
Viewed 0 times
storedthepassingintoproceduretable
Problem
Is it possible to pass in the name of a table into a stored procedure?
For example, suppose you have several views of the same table. They all have the exact same structure.
You want a stored procedure that can be run for any of the views.
Something like:
When I try to do this, I get
Any ideas how I can do this?
For example, suppose you have several views of the same table. They all have the exact same structure.
You want a stored procedure that can be run for any of the views.
Something like:
create procedure myprocedure
@tableName varchar(50) = ''
select blah from @tableName where blah = blah2When I try to do this, I get
Must declare the table variable @tablenameAny ideas how I can do this?
Solution
Object names cannot be parameterized.
You need to use dynamic SQL:
Note that
You need to use dynamic SQL:
CREATE PROCEDURE MyProc
(
@schemaName sysname,
@tableName sysname,
@blah2 int
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @sql nvarchar(MAX)
SET @sql = N'SELECT blah FROM '
+ QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + N' WHERE blah = @blah2'
EXEC sp_executesql @sql, N'@blah2 int', @blah2
ENDNote that
sysname is (currently) defined as nvarchar(128).Code Snippets
CREATE PROCEDURE MyProc
(
@schemaName sysname,
@tableName sysname,
@blah2 int
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @sql nvarchar(MAX)
SET @sql = N'SELECT blah FROM '
+ QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + N' WHERE blah = @blah2'
EXEC sp_executesql @sql, N'@blah2 int', @blah2
ENDContext
StackExchange Database Administrators Q#19564, answer score: 11
Revisions (0)
No revisions yet.