34,594
社区成员
发帖
与我相关
我的任务
分享
row_number() over(order by getdate())
之前我也想这样写,但是我觉得上边这个rn,不是固定的,但是我不太清楚受什么影响,rn的值一样可能下次对应的数据库里的行就不一样,不知道我理解的对不对。
-- 建测试表
create table ABC_TAB(col1 varchar(10),col2 varchar(10),col3 varchar(10),col4 varchar(10))
insert into ABC_TAB
select '11','row1','test1','test111' union all
select '22','row2','test2','test222' union all
select '33','row3','test3','test333' union all
select '44','row4','test4','test444'
-- 更改的数据对应的行列号
declare @updaterow int,@updatecol int,@newvalue nvarchar(100)
select @updaterow=2,@updatecol=3,@newvalue=N'HELLO' --> 更改第2行第3列的数据为 “HELLO”
declare @tsql nvarchar(1000)
select @tsql=N'update t set '
+(select top 1 N'['+b.name+N']=N'''+@newvalue+N''' '
from sys.tables a
inner join sys.columns b on a.object_id=b.object_id
where a.name=N'ABC_TAB'
and b.column_id=@updatecol)
+N' from (select rn=row_number() over(order by getdate()),* from ABC_TAB) t '
+N' where t.rn='+rtrim(@updaterow)
exec(@tsql)
-- 结果
select * from ABC_TAB
/*
col1 col2 col3 col4
---------- ---------- ---------- ----------
11 row1 test1 test111
22 row2 HELLO test222
33 row3 test3 test333
44 row4 test4 test444
(4 行受影响)
*/
UPDATE ABC_TAB set 字段名="HELLO" where XXXX--这里规定是哪一行