我有TaxTable主键出租车 结构如下
taxid Type noteID
1 A
2 G
3 G
4 G
我也有一张noteTable表格看起来像这样
NoteID SNoteText
456 Hellow joe
457 Non-Taxable
458 Non-Taxable
459 Non-Taxable
现在我需要填充taxType = G,其中noteID为Snotetext = Non-Taxable
所以最终结果将如下:
taxid Type noteID
1 A
2 G 457
3 G 458
4 G 459
我希望有道理。谢谢你的帮助
答案 0 :(得分:1)
如果您之间没有表格链接,请创建表格。像这样:
create table #taxTable(taxid int, [type] char(1),noteID int)
insert #taxTable(taxid,[type])
values (1,'A'),(2,'G'),(3,'G'),(4,'G'),
(5,'A'),(6,'G'),(7,'G'),(8,'G'),(9,'G')
create table #noteTable(NoteID int,SNoteText varchar(50))
insert #noteTable
values
(456, 'Hellow joe'),
(457 ,'Non-Taxable'),
(458 ,'Non-Taxable'),
(459 ,'Non-Taxable')
declare @cnt int
select @cnt=COUNT(noteid) from #noteTable where SNoteText='Non-Taxable'
-- It is possible to add 3rd CTE for cnt
;with n as (select row_number() over(order by noteID) rn,
noteId
from #noteTable where SNoteText='Non-Taxable'),
t as (select row_number() over(order by taxid) rn,
taxid,[type], noteid from #taxtable where [type]='G')
update t
set noteID = n.noteid
from n inner join t on n.rn= (t.rn%@cnt)+1
select * from #taxtable