简体   繁体   English

如何在 mssql 中循环表列并创建条件插入语句

[英]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.

相关问题 如何编写条件选择插入语句以从表中获取记录,并基于某些特定列的值 - How to write conditional select insert statement to fetch record from a table, and based on some particular column's values 带有条件目标列的插入语句 - Insert statement with a conditional target column 如何从MSSQL中的另一个表的列值创建表结构 - how to create a table structure from column values of another table in MSSQL 如何在一个语句中创建表并插入值 - How to create table and insert values in one statement MSSQL插入嵌套语句 - MSSQL insert with nested statement WITH 语句无限循环 - MSSQL - WITH statement endless loop - MSSQL 将这些记录插入mssql中的另一个表后,如何逐行循环更新数据? - How can I update the data row by row by the loop after insert those records into another table in mssql? 如何使用基于另一个select语句的循环插入表中 - How to insert into a table using loop based on another select statement 具有增量整数列的MSSQL Select语句…不是来自表 - MSSQL Select statement with incremental integer column… not from a table 如何在访问中创建基于另一个表的条件总和的计算列 - How to create a calculated column in access that is based in a conditional sum of another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM