请问以下SQL语句为何不正确?

来源:百度知道 编辑:UC知道 时间:2024/06/01 04:31:02
declare @id int
declare @str nvarchar(5)
set @id=1
set @str=N'模块'
while @id<=10
begin
insert into testmodule(modulename) values(@str+@id)
set @id=@id+1
end
--以上运行总提示不能将‘模块’转换成INT型。将@id写成cast(@id as nvarchar(2)也不行,因为又提示set @id=@id+1 错误。以上是在SQL2005中运行。实在想不出原因,请高手帮忙解答!
abczjwz:你的答案有点看不懂,而且运行也不能通过。convert(char(10),N)??? N是unicode格式的符号。

@str是nvarchar型,@id是int型,要进行字符串连接的话,应该先将@id转成nvarchar行再与@str做连接。

declare @id int
declare @str nvarchar(10)
set @id=1
set @str=N'模块'
while @id<=10
begin
insert into testmodule(modulename) values(@str+ cast(@id as nvarchar)
set @id=@id+1
end

还有一点,声明@str是,文本长度设置5,太小。当ID>9时,还是会出错。不妨改大点

set @str=N'模块'

select @str = rtrim(convert(char(10),N))+'模块'

insert into testmodule(modulename) values(@str+@id)

这句改为exec('insert into testmodule(modulename) values('+@str+
cast(@id as nvarchar(2)+')' )

这样就可以了。

祝你好运!