简体   繁体   中英

How to loop a table column and create conditional insert statement in mssql

I want to loop CustomerType column in CustomerDetails table. then use the condition where CustomerType = 'CorporateCustomer' to update IsCorporateCustomer column to 1 and else update others to 0

This is what I did but It only executes the first statement and added 1 to all the IsCorporateCustomer column.

How can I fix this? Thanks

IF EXISTS (SELECT * FROM CustomerDetails WHERE CustomerType =  'CorporateCustomer')
BEGIN
UPDATE CustomerDetails set IsCorporateCustomer = 1;
END
ELSE
BEGIN
UPDATE CustomerDetails set IsCorporateCustomer=0;
END

you can use case statement, so your whole statement above will be as simple as below query:

UPDATE CustomerDetails 
set IsCorporateCustomer = case when CustomerType =  'CorporateCustomer' then 1 else 0 end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM