sp_executesql函数遇到的一个问题。
作者:shaic 日期:2008-1-18 来源:原创
executesql 是 SQL Server 的一个存储过程,用于执行一个 SQL 语句。
语法:
sp_executesql [@stmt =] stmt
[
{, [@params =] N'@parameter_name data_type [,...n]' }
{, [@param1 =] 'value1' [,...n] }
]
下面是在做一个连环复制插入数据表中相同数据事例,用到executesql
CREATE TABLE table1 (
id int IDENTITY (1, 1) NOT NULL ,
[title] varchar(50)
)
insert into table1(title) values('11')
insert into table1(title) values('22')
insert into table1(title) values('33')
insert into table1(title) values('44')
select * from table1
-------------------------------------------------------------
declare @id int
declare @j int
declare @k int
declare @strsql nvarchar(400)---一定要设为nvarchar,不是varchar
select @k=count(1) from table1
set @j=0
while (@j<@k)
begin
set @strsql='select @id=id from table1 where id not in(select top '+cast(@j as varchar)+' id from table1) order by id desc'
--print @strsql
EXEC sp_executesql @strsql,N'@id int output',@id output
insert into table1(title) select (title + '_' + cast(@@identity + 1 as varchar)) from table1
where id=@id
set @j=@j+1
end
不知道为什么@strsql 非要设为nvarchar,浪费了几个小时时间,做个记录,
查看次数: 104