sql - 如何使用局部变量或用户定义函数更新表?
问题描述
我正在尝试通过将“用户名”设置为“名称”的产品来更新我的表。
这是我的例子:
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”
解决方案
简单update
的语句也可以,不需要使用变量:
update @t
set username = replace(lower(name), ' ', '.')
编辑 :
如果您只想在变量的帮助下更新单个值,那么您可以执行以下操作:
select @username = replace(lower(name), ' ', '.')
from @t
where name = @username;
推荐阅读
- rotation - 处理 3.5.3 围绕中心点旋转点 图像缩小消失
- visual-studio - 如何在 Visual Studio 2017 中远程调试到以前部署的以调试模式构建的应用程序?
- sql - How can I create a selection that can show my total of objects by owners?
- schema.org - 为什么 Google 说一个项目需要 schema.org 中的 url 属性?
- docusignapi - JWT OAuth 身份验证流程中的“错误请求”消息
- android - 使用 Espresso 同时测试两项活动
- azure - Azure SQL Server 中的批量插入权限问题
- python - Django Tags 保存相关对象
- unity3d - 根据forward旋转位置
- javascript - 如何记住一个方法是否改变了原始数组?