How to specify a table dynamically in a Stored Procedure
Thanks for 开发者_JAVA百科the feedback, but I was hoping for help with an UPDATE command, not SELECT. Can anyone help with the syntax for an UPDATE command?
I am passing a table name into a Stored Procedure but the SQL does not seem to recognize it.
DECLARE @userTable AS VARCHAR(200);
SET @userTable = @currTable
UPDATE @userTable
SET [lang_String] = @lang_String, [date_Changed] = @submitDate1
WHERE (ID = @ID)
@currTable
is passed into the Stored Procedure. All tables names are built by design in code.
You can't, you need to build the entire SQL string and then execute it, like this for example:
DECLARE @sql nvarchar(4000)
SELECT @sql = ' SELECT col1, col2, col3 ' +
' FROM dbo.' + quotename(@tblname) +
' WHERE keycol = @key'
EXEC sp_executesql @sql, N'@key varchar(10)', @key
Got this to work quite easily....
@myTable varchar(150)
/* Comments:
*/
AS
SET NOCOUNT ON;
DECLARE @sql varchar(max);
SET @sql = 'SELECT [ID], [StringID], [GUID] FROM ' + @myTable + ' ORDER BY [GUID]';
print (@sql)
EXECUTE(@sql);
SET @langTable = Null;
FYI, the values available for myTable are stored in another table and are not available to users for edit. Table names are built dynamically in code based on a unique combination of values.
精彩评论