答案 0 :(得分:1)
如果你只有几个,你可以做D-Shih的建议
如果列Attempts
为空时有很多出现,则可以先生成所有更新命令。
所以实际上你正在使用两个步骤
第一步:生成所有更新命令
select 'update original_table set systemID = ''' + SystemID + ''' where StudentID = ' + convert(varchar, t.studentID)
from original_table t
where Attempts is null
第2步:执行所有命令
现在你得到一个记录集,其中包含你需要执行的所有更新命令 只需将其复制并执行即可。
最后删除空尝试
delete from original_Table where Attempts is null
如果生成的更新命令正确,请不要忘记检查生成的更新命令...
答案 1 :(得分:1)
我假设您的表中有其他systemId,因此您可以在一次更新中为整个表执行此操作
DECLARE @systemId NVARCHAR(10)
DECLARE @tb table (StudentId int , attempts int , systemId nvarchar(10))
INSERT INTO @tb
VALUES (105,0,'CRU877'),
(105,1,NULL),
(105,2,NULL),
(105,3,NULL),
(106,0,'AUR145'),
(106,1,NULL),
(106,2,NULL),
(106,3,NULL),
(106,4,NULL)
/*Before*/
SELECT *
FROM @tb
UPDATE @tb
SET @systemId = systemId = CASE WHEN systemId IS NULL THEN @systemId ELSE systemId END
/*After*/
SELECT *
FROM @tb
WHERE attempts != 0
答案 2 :(得分:0)
试试这个:
数据生成:
declare @x table(studentId int, attempts varchar(2), systemId varchar(10))
insert into @x values
(105, '1', ''),
(105, '2', ''),
(105, '3', ''),
(105, '', 'CRU877'),
(106, '1', ''),
(106, '2', ''),
(106, '3', ''),
(106, '4', ''),
(106, '', 'AUR145')
更新查询:
update @x set systemId = sysId from (select studentId [stdId], systemId [sysId] from @x where attempts = '') [x] where studentId = stdId
delete @x where attempts = ''
select * from @x
你附加的图片非常暧昧,我不知道空白单元格是NULL
还是空字符串。以防万一有解决方案考虑到这一点:
declare @x table(studentId int, attempts int, systemId varchar(10))
insert into @x values
(105, 1, null),
(105, 2, null),
(105, 3, null),
(105, null, 'CRU877'),
(106, 1, null),
(106, 2, null),
(106, 3, null),
(106, 4, null),
(106, null, 'AUR145')
update @x set systemId = sysId from (select studentId [stdId], systemId [sysId] from @x where attempts is null) [x] where studentId = stdId
delete @x where attempts is null
select * from @x
答案 3 :(得分:0)
声明表变量,使用update + join组合更新原始表,然后在原始表上运行delete语句。
声明@systemIDs表(studentID int,systemID varchar(50))
插入@systemIDs
从original_tbl中选择studentID,systemID,其中systemID不为null
更新ot设置ot.systemID = si.systemID from original_tbl ot inner join @systemIDs si on ot.studentID = si.studentID
从original_tbl中删除,其中尝试为空