动态sql语句如何引用数字变量

时间:2021-02-10 19:15:05
代码如下
declare @uid int;
set @uid=7;

declare @sql nvarchar(1000);
set @sql='select * from [aaa] where uid= ' @uid
exec(@sql)

提示
消息 245,级别 16,状态 1,第 9 行
在将 varchar 值 'select * from [aaa] where uid= ' 转换成数据类型 int 时失败。

如果我把@uid定义成varchar就没问题,这是怎么回师,谢谢,该怎么解决

declare @uid int;
set @uid=7;

declare @sql nvarchar(1000);
set @sql='select * from [aaa] where uid= ' rtrim(@uid)
exec(@sql)

declare @uid int
set @uid=7

declare @sql nvarchar(1000)
set @sql='select * from [aaa] where uid= ' cast(@uid as nvarchar)
exec(@sql)

declare @uid int;
set @uid=7;

declare @sql nvarchar(1000);
set @sql=N'select * from [aaa] where uid=@uid'
exec sp_executesql @sql,N'@uid int',@uid