动态sql详谈动态指定表名 列名(exec sql_executesql)

本文探讨了在SQL中使用exec和execsp_executesql时避免使用参数形式的表名和列名的方法。通过两种方案——使用变量和存储过程参数,解决了动态SQL中常见的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--在动态sql中,无论exec还是exec sp_executesql,都不允许使用参数形式的表名和列名,
--你可以使用变量或者在存储过程中使用存储过程参数声明部分的参数,而不是直接使用
--exec sp_executesql参数声明部分的参数

--典型的错误代码(there is no wrong with grammer,but not any row is returned)
declare @outPutValue as int,
@schemaname as nvarchar(50),
@tablename as nvarchar(50),
@filtercolumn as nvarchar(50),
@columnvalue as nvarchar(50),
@sql nvarchar(max);
set @schemaname='dbo';
set @tablename='orders';
set @filtercolumn='employeeid';
set @columnvalue='1';
set @sql='select count(*) from '+quotename(@schemaname)+'.'+quotename(@tablename)
+' where @fc=@cv ';--使用了参数形式的列名 the error occur
exec sp_executesql
@sql,
N'@fc as nvarchar(50),@cv as nvarchar(50),@outValue as int output',
@fc=@filtercolumn,
@cv=@columnvalue,
@outValue=@outPutValue output;
print @outPutValue;
print @sql;

--solution 1-----使用变量的方式为动态sql静态提供选择列,表名,过滤列
--此解决方案并展示了如何使用exec sp_executesql的输出参数
use northwind;
go
declare @outPutValue as int,
@schemaname as nvarchar(50),
@tablename as nvarchar(50),
@filtercolumn as nvarchar(50),
@columnvalue as nvarchar(50),
@countname as nvarchar(50),
@sql nvarchar(max);
set @schemaname='dbo';
set @tablename='orders';
set @filtercolumn='employeeid';
set @columnvalue='1';
set @countname='orderid';
set @sql='select @outValue=count('+@countname --使用了输出参数
+') from '
+quotename(@schemaname)+'.'+quotename(@tablename)
+' where '+@filtercolumn+'=@cv ';
exec sp_executesql
@sql,
N'@fc as nvarchar(50),@cv as nvarchar(50),@outValue as int output',
@fc=@filtercolumn,
@cv=@columnvalue,
@outValue=@outPutValue output;--使用输出参数为变量@outPutValue赋值,变量后加关键字output
print @outPutValue;
print @sql;
go

--solution 2-使用存储过程的参数为动态sql动态提供选择列,表名,过滤列
use NorthWind;
go
alter PROCEDURE GetData
@tbName nvarchar(50),
@colName nvarchar(50),
@Name nvarchar(50),
@filtername nvarchar(50)
AS
BEGIN
declare @sql nvarchar(max);
set @sql='select '+ @colName+' from ' +@tbName+ ' where '+@filtername+'=@whereName';
--注意此句不可以写成如下:
-- set @sql='select @colName from @tbName where employeeid=@whereName';
exec sp_executesql
@sql,
N'@whereName nvarchar(20)',
@Name
print @sql;
END

exec GetData
@name=N'1',
@tbName=N'dbo.Orders',
@colName=N'employeeid',
@filtername=N'employeeid';

 


conclusion:solution1 和solution 2 都成功避开了,不能直接使用参数形式的列名和表名的限制,
solution1使用的变量的方式是静态的,
solution2使用的是存储过程的参数的方式是动态的,这种方式可用性更强。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值