这样的字符串不知道怎么拼接才正确
create table table_1 (a varcher(50) b datetime)
然后向表插入一天记录。
decleare @aa varchar(50)
declare @bb datetime
declare @sqlstr varchar(1000)
select @aa=a,@bb=b from table_1
set @sqlstr=''
请问 我该如何拼接才能把 'select @aa=a,@bb=b from table_1' 让EXEC @sqlstr 正确执行,这两个变量还有个是日期型的。
------解决方案--------------------
给你一个拼接的例子:
if object_id('Class') is not null
drop table Class
Go
Create table Class(
[Student] nvarchar(2),
[Course] nvarchar(2),
[Score] int)
Insert Class
select N'张三',N'语文',78 union all
select N'张三',N'数学',87 union all
select N'张三',N'英语',82 union all
select N'张三',N'物理',90 union all
select N'李四',N'语文',65 union all
select N'李四',N'数学',77 union all
select N'李四',N'英语',65 union all
select N'李四',N'物理',85
Go
--2000方法:
--动态:
declare @s nvarchar(4000)
set @s=''
Select @[email protected]+','+quotename([Course])+'=max(case when [Course]='
+quotename([Course],'''')+' then [Score] else 0 end)'
from
Class group by[Course]
--select @s
exec('select [Student][email protected]+' from Class group by [Student]')
自己参考一下
------解决方案--------------------
------解决方案--------------------
set @sqlstr='select a = ''' + @a + ''' , b = ''' + convert(varchar(20),@bb,120) + ''' from table_1'
------解决方案--------------------
- SQL code
declare @str nvarchar(max)declare @aa varchar(50)declare @bb datetimeset @str = N'select @aa=a,@bb=b from table_1'exec sp_executesql @str,[email protected] varchar(50) output,@bb datetime output',@aa output,@bb outputselect @aa,@bb