0

I am using SQL Server 2014. I want to update one column, then after this column use in second update statement in dynamically generated query.

My query looks like this:

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 

but this is not working.

My table looks like this:

name    email          phone            a   b
----------------------------------------------
s       [email protected]          111            NULL 1
u       [email protected]        222            NULL 1
x       qww             333            NULL 1
ik      [email protected]     1234567890     NULL 1
kinjal  [email protected]     7894561230     NULL 1

2 Answers 2

1

the single quotes inside a string must be "doubled". It should look like this:

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 
Sign up to request clarification or add additional context in comments.

2 Comments

can you please provide sample data for tblchild and tblmaster? to which table belong the sample data in your question?
this data is for tblChild
0

I found the problem!!!

I create key from phone and a column and than update. But my column a is null so it's can't merge.

use

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

instead of

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

1 Comment

ok so there was a data-driven problem too - didn't see that but i edited my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.