如果 SQL 有字典和 for-each,则在 table 中插入新值
Inserting new values in a table if SQL had Dictionary and for-each
假设我的 table of myTable
有一个 column1,其中已经有一些值。
现在我得到了一些新值,我应该将它们放入名为 'column2
' 的新创建的列中。
它们是一对一关联在一起的,并且是唯一的。例如:
column1 | column2
-----------------
'ABCHi' | 'newOH'
-----------------
'TER12' | 'Meow2'
-----------------
'WhatE' | 'BMW26'
-----------------
所以我可以这样说:
Update myTable SET column2 = 'newOH' WHERE column1 = 'ABCHi'
并对每一行都这样做(我有 32 行要做)。
但我想也许有一种“更好”的方式来做到这一点?就像是 C#
我可以说填充一个 dictionary
然后做一个 for-each
循环!
您可以使用 With 子句将“词典”创建为内联视图。
这里是fiddlehttps://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=c0e1393785082fd5cd9352d513b76af6
with Dictionary as(
select 'ABCHi' as column1, 'newOH' as column2
union all
select 'TER12' as column1, 'Meow2' as column2
union all
select 'WhatE' as column1, 'BMW26' as column2
)
UPDATE t
SET t.column2=dictionary.column2
FROM mytable t JOIN Dictionary ON t.column1 = Dictionary.column1
您可以使用 Table Value Constructor:
declare @Samples as Table ( Column1 VarChar(10), Column2 VarChar(10) );
-- Initialize the sample data.
insert into @Samples ( Column1 ) values
( 'ABCHi' ), ( 'TER12' ), ( 'WhatE' )
select * from @Samples;
-- Update the second column.
update OSamples
set Column2 = NSamples.Column2
from @Samples as OSamples inner join
( values
( ( 'ABCHi' ), ( 'newOH' ) ),
( ( 'TER12' ), ( 'Meow2' ) ),
( ( 'WhatE' ), ( 'BMW26' ) )
) as NSamples( Column1, Column2 )
on OSamples.Column1 = NSamples.Column1;
select * from @Samples;
假设我的 table of myTable
有一个 column1,其中已经有一些值。
现在我得到了一些新值,我应该将它们放入名为 'column2
' 的新创建的列中。
它们是一对一关联在一起的,并且是唯一的。例如:
column1 | column2
-----------------
'ABCHi' | 'newOH'
-----------------
'TER12' | 'Meow2'
-----------------
'WhatE' | 'BMW26'
-----------------
所以我可以这样说:
Update myTable SET column2 = 'newOH' WHERE column1 = 'ABCHi'
并对每一行都这样做(我有 32 行要做)。
但我想也许有一种“更好”的方式来做到这一点?就像是 C#
我可以说填充一个 dictionary
然后做一个 for-each
循环!
您可以使用 With 子句将“词典”创建为内联视图。
这里是fiddlehttps://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=c0e1393785082fd5cd9352d513b76af6
with Dictionary as(
select 'ABCHi' as column1, 'newOH' as column2
union all
select 'TER12' as column1, 'Meow2' as column2
union all
select 'WhatE' as column1, 'BMW26' as column2
)
UPDATE t
SET t.column2=dictionary.column2
FROM mytable t JOIN Dictionary ON t.column1 = Dictionary.column1
您可以使用 Table Value Constructor:
declare @Samples as Table ( Column1 VarChar(10), Column2 VarChar(10) );
-- Initialize the sample data.
insert into @Samples ( Column1 ) values
( 'ABCHi' ), ( 'TER12' ), ( 'WhatE' )
select * from @Samples;
-- Update the second column.
update OSamples
set Column2 = NSamples.Column2
from @Samples as OSamples inner join
( values
( ( 'ABCHi' ), ( 'newOH' ) ),
( ( 'TER12' ), ( 'Meow2' ) ),
( ( 'WhatE' ), ( 'BMW26' ) )
) as NSamples( Column1, Column2 )
on OSamples.Column1 = NSamples.Column1;
select * from @Samples;