[英]How to loop a table column and create conditional insert statement in mssql
I want to loop CustomerType column in CustomerDetails table.我想在 CustomerDetails 表中循环 CustomerType 列。 then use the condition where CustomerType = 'CorporateCustomer' to update IsCorporateCustomer column to 1 and else update others to 0
然后使用 CustomerType = 'CorporateCustomer' 的条件将 IsCorporateCustomer 列更新为 1,否则将其他列更新为 0
This is what I did but It only executes the first statement and added 1 to all the IsCorporateCustomer column.这就是我所做的,但它只执行第一条语句并将 1 添加到所有 IsCorporateCustomer 列。
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:您可以使用 case 语句,因此您上面的整个语句将与以下查询一样简单:
UPDATE CustomerDetails
set IsCorporateCustomer = case when CustomerType = 'CorporateCustomer' then 1 else 0 end;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.