在SQL Server中的动态查询中执行多个更新语句

时间:2015-07-03 08:30:42

标签: sql-server

我正在使用SQL Server 2014.我想更新一个列,然后在此列中使用动态生成的查询中的第二个更新语句。

我的查询如下:

declare @squery varchar(max)
set @squery =   'if('+CHAR(39)+@AppendType+CHAR(39)+' = ''Address'')
begin
    update tblchild set name=(REPLACE(LEFT(phone,2)+LEFT(a,1),' ',''))
    update a  set a.a=a.name,a.name = b.name,a.email= b.email,a.b = '1' from tblchild as a , tblmaster as b where a.phone = b.phone
    update a  set a.name = b.name,a.phone = b.phone,a.a=b.a,a.b = '1' from tblchild as a , tblmaster as b where a.email = b.email and (a.b IS NULL or a.b = '')
end'

print(@squery)  
exec (@squery)

select * from tblchild 

但这不起作用。

我的表格如下:

name    email          phone            a   b
----------------------------------------------
s       z@a.in          111            NULL 1
u       a@ghf.ij        222            NULL 1
x       qww             333            NULL 1
ik      k@gmail.com     1234567890     NULL 1
kinjal  kin@abc.com     7894561230     NULL 1

2 个答案:

答案 0 :(得分:1)

字符串中的单引号必须是"加倍"。它应该是这样的:

declare @squery nvarchar(max)
declare @AppendType nvarchar(max) = N'Address'

set @squery =   N'if('+CHAR(39)+@AppendType+CHAR(39)+N' = ''Address'')
begin
    update tblchild set name=(REPLACE(LEFT(phone,2)+LEFT(ISNULL(a,''''),1),'' '',''''))
    update a  set a.a=a.name,a.name = b.name,a.email= b.email,a.b = ''1'' from tblchild as a , tblmaster as b where a.phone = b.phone
    update a  set a.name = b.name,a.phone = b.phone,a.a=b.a,a.b = ''1'' from tblchild as a , tblmaster as b where a.email = b.email and (a.b IS NULL or a.b = '''')
end'

print(@squery)  
execute sp_executesql @squery

select * from tblchild 

答案 1 :(得分:0)

我发现了问题!!!

我从phonea列创建了密钥而不是更新。但我的专栏a为空,因此无法合并。

使用

update tblchild set name=(REPLACE(LEFT(phone,2)+LEFT(ISNULL(a,''''),1),'' '',''''))

而不是

update tblchild set name=(REPLACE(LEFT(phone,2)+LEFT(a,1),' ',''))