首页 > 解决方案 > 如何使用局部变量或用户定义函数更新表?

问题描述

我正在尝试通过将“用户名”设置为“名称”的产品来更新我的表。

这是我的例子:

declare @username varchar(128)

-- create local table
declare @t table (name varchar(32), username varchar(32))
insert into @t(name, username) values ('Johnny Cash','')

-- update rows, set "username" to its correct value
;with mytable as (select * from @t)
update mytable
-- this is really messy, I want to use some local variables or a user-defined function here to compute the username...
set username = lower(substring(name, 0, charindex(' ', name)) + '.' + substring(name, charindex(' ', name)+1, len(name)))

-- select all rows so I can see them
;with mytable as (select * from @t)
select * from mytable

对于每一行,我希望用户名与名称相同但有一些修改。

这可能吗?

澄清一下,我希望名称为“Johnny Cash”的行有一个用户名“johnny.cash”

标签: sqlsql-server

解决方案


简单update的语句也可以,不需要使用变量

update @t
     set username = replace(lower(name), ' ', '.')

编辑 :

如果您只想在变量的帮助下更新单个值,那么您可以执行以下操作:

select @username = replace(lower(name), ' ', '.')
from @t
where name = @username;

推荐阅读