July 8, 2014 at 7:43 am
I'm trying to parameterise code executed by sp_executesql. It's not a stored procedure, I've just got a number of similar SQL scripts, and trying to minimise the edits involved.
Here is some sample code (simplified example):
declare @tablename nvarchar(255);
declare @colname nvarchar(255);
declare @parms nvarchar(255);
declare @sql nvarchar(max);
set @tablename=N'sys.objects';
set @colname=N'name';
set @parms=N'@tablename nvarchar(255)';
set @sql=N'select top 5 * from @tablename';
exec sp_executesql @sql, @parms, @tablename;
------------------------------------------------
declare @tablename nvarchar(255);
declare @colname nvarchar(255);
declare @parms nvarchar(255);
declare @sql nvarchar(max);
set @tablename=N'sys.objects';
set @colname=N'name';
set @parms=N'@colname nvarchar(255)';
set @sql=N'select top 5 @colname from sys.objects';
exec sp_executesql @sql, @parms, @colname;
------------------------------------------------
declare @tablename nvarchar(255);
declare @colname nvarchar(255);
declare @parms nvarchar(255);
declare @sql nvarchar(max);
set @tablename=N'sys.objects';
set @colname=N'name';
set @parms=N'@tablename nvarchar(255), @colname nvarchar(255)';
set @sql=N'select top 5 @colname from @tablename';
exec sp_executesql @sql, @parms, @tablename, @colname;
Highlight each separate section and submit in SSMS.
I'm following the examples in here: http://msdn.microsoft.com/en-au/library/ms188001.aspx.
If I have to generate code like:
set @sql=N'select top 5 ' + @colname + ' from ' + @tablename;
Then I may consider this approach instead, especially when double- and triple-quoting is involved:
set @sql=N'select top 5 <<colname>> from <<tablename>>';
set @sql=replace(@sql,'<<colname>>',@colname);
set @sql=replace(@sql,'<<tablename>>',@tablename);
exec(@sql);
Thank you for pointing me in the right direction.
July 8, 2014 at 7:52 am
You can't parameterise table or column names. You'll have to build up the string with those values in (and beware SQL injection vulnerabilities)
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
July 9, 2014 at 7:09 am
You parameterize the values passed to the query, not the tables and columns. Those have to be explicitly stated. As Gail said, you can build those statements dynamically, but you better have great syntax checking to ensure you don't hit SQL Injection.
"The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
- Theodore Roosevelt
Author of:
SQL Server Execution Plans
SQL Server Query Performance Tuning
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply