sql server 字符串连接 存储过程

来源:百度知道 编辑:UC知道 时间:2024/05/14 09:04:07
在sqlserver 2005中编写存储过程,需要将变量写入表中,变量是varchar型的,不过是经过字符串连接的,但是insert的时候就总是失败,不知道为什么,请大家帮忙。
下面是存储过程中的语句:
select @vday=substring(convert(varchar(12),getdate(),112),7,2)
select @vmonth=substring(convert(varchar(12),getdate(),112),5,2)
select @vdate=@vday+'/'+@vmonth

set @vsql='insert into table1 select '+'''abc'''+','+@vdate+' from table2'
exec (@vsql)

使用print打印变量可以看到@vdate是正常的,但是通过exec (@vsql)后这个字段就总是为空,也没有错误提示。
我试过直接写一个常量进去就可以看到,应该是不识别这个@vdate为字符型。
但是我使用过convert和cast函数进行字符转换,但结果都一样。
请大家帮忙看看,谢谢

这句代码应该这样写,我已经测试过,请放心使用:
set @vsql='insert into table1 select ''abc''+'''+@vdate+''' from table2'

以上,希望对你有所帮助!

1.检查table2是否有数据。
2.set @vsql='insert into table1 select '+'''abc'''+','+@vdate+' from table2'
改成
set @vsql='insert into table1 select '+'''abc'''+','''+@vdate+''' from table2'