首页 > 解决方案 > 更新表并添加新列,检查用户名编号的所有行 | SQL 服务器

问题描述

我需要添加这个脚本

ALTER TABLE [dbo].[MyTable]
    ADD [MyNewColumnCheckUserName] BIT NOT NULL DEFAULT 0;

MyTable但是更新后,如果 UserName 只有数字,我需要检查所有旧行- 所有 UserName(它是此表中的列)?如果是 - 将此行设置为 true MyNewColumnCheckUserName

标签: sqlsql-server

解决方案


您可以使用:

update mytable
    set MyNewColumnCheckUserName = (case when UserName like '%[^0-9]%' then 0 else 1 end);

但是,我建议将其添加为计算列:

alter table mytable add MyNewColumnCheckUserName as 
    (case when UserName like '%[^0-9]%' then 0 else 1 end);

我知道没有理由更喜欢位而不是计算列的数字但是如果你真的想招致 a 的开销bit,你可以转换这个值:

alter table mytable add MyNewColumnCheckUserName as 
    (convert(bit, (case when UserName like '%[^0-9]%' then 0 else 1 end));

推荐阅读