[英]How to update a table with list of values in T-SQL?
I have a table that I want to update one-to-many relationship records.我有一个要更新一对多关系记录的表。 The table def is:表定义为:
CREATE TABLE CT_ProductFailures
(
PFID int identity(1,1) PRIMARY KEY NOT NULL,
Old_Modes varchar(75),
New_Modes varchar(75)
)
Now I want to add records for New_Mode 'N1' with Old_Modes 'A', 'B', 'C'.现在我想用 Old_Modes 'A'、'B'、'C' 添加 New_Mode 'N1' 的记录。 Other than by doing separate insert statements, how can I achieve this?除了通过单独的插入语句之外,我怎样才能做到这一点?
If you are using SQL Server 2008 you can do this rather easily using syntax like below如果您使用的是 SQL Server 2008,您可以使用如下语法轻松完成此操作
INSERT INTO CT_ProductFaiures (Old_Modes, New_Modes)
VALUES ('N1', 'A'), ('N1', 'B'), ('N1', 'C');
This assumes PFID is auto incrementing.这假设 PFID 是自动递增的。
You can use UNIONS do sort of achieve this in older versions.您可以在旧版本中使用 UNIONS 来实现这一点。 Check out the link below for great examples.查看下面的链接以获取很好的示例。
http://blog.sqlauthority.com/2008/07/02/sql-server-2008-insert-multiple-records-using-one-insert-statement-use-of-row-constructor/ http://blog.sqlauthority.com/2008/07/02/sql-server-2008-insert-multiple-records-using-one-insert-statement-use-of-row-constructor/
INSERT INTO CT_ProductFailures (New_Modes, Old_Modes)
SELECT n.New_Modes, o.Old_Modes
FROM (SELECT 'N1' New_Modes) n
CROSS JOIN (SELECT 'A' Old_Modes
UNION ALL SELECT 'B'
UNION ALL SELECT 'C') o
Alternatively, write a split function using newline as the separator:或者,使用换行符作为分隔符编写一个拆分 function :
INSERT INTO CT_ProductFailures (New_Modes, Old_Modes)
SELECT 'N1' New_Modes, o.value Old_Modes
FROM dbo.split(
'A
B
C') o
Ryan,瑞安,
You are saying: 'Instead I want to copy this list so that all I have to do is add single quotes around each record'.你是说:'相反,我想复制这个列表,这样我所要做的就是在每条记录周围添加单引号'。
It is not clear how your list is formated.目前尚不清楚您的列表是如何形成的。
Let's assume you have the list like this (comma separated values)假设您有这样的列表(逗号分隔值)
N1, A
N1, B
N1, C
What you can do is:你可以做的是:
Run some replacements using regular expressions:使用正则表达式运行一些替换:
You will end up with the list like this:你最终会得到这样的列表:
('N1', 'A'), ('N1', 'B'), ('N1', 'C')
Then add insert statement at the top of the script:然后在脚本顶部添加插入语句:
insert into CT_ProductFaiures (Old_Modes, New_Modes) values
So in the result you have this所以结果你有这个
insert into CT_ProductFaiures (Old_Modes, New_Modes)
values
('N1', 'A'),
('N1', 'B'),
('N1', 'C')
Hope that this is what you needed.希望这是您所需要的。
[Edited] [已编辑]
I'm sorry, didn't pay attention.不好意思,没注意。
So list is formatted like this: A, B, C, D.所以列表的格式如下:A,B,C,D。
Then you just replace [,] with ['), ('N1', '] without any regular expressions.然后,您只需将 [,] 替换为 ['), ('N1', '] 即可,无需任何正则表达式。
Also, fix starting and ending value manually.此外,手动修复开始和结束值。
Create a table called NewTable with the AB C records with another New_Modes field.使用 AB C 记录和另一个 New_Modes 字段创建一个名为 NewTable 的表。
Use this table in your insert command.在您的插入命令中使用此表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.