将动态长度数组插入并更新到表中

时间:2014-01-07 11:59:30

标签: c# sql-server arrays stored-procedures

我的桌子是

(id int,property varchar)  

假设我要插入{3, 'a, b, c'}。如何在存储过程中执行此操作? 表条目是:

id property  
3   a  
3   b  
3   c  

此外,当我想按id=3更新{3, 'ab, b, bg, ht'}行时。此插入和更新操作的存储过程是什么?我的表条目应该成为

id property  
3   ab  
3   b  
3   bg  
3   ht 

4 个答案:

答案 0 :(得分:3)

样本表:

create table yourtable (id int,property varchar(5))

该表的程序:

create procedure p_test
(
@id int, 
@prolist varchar(2000)
) as
begin
;with x as
(
  SELECT * FROM yourtable WHERE id = @ID
)
MERGE INTO 
x t1 
using 
(SELECT @id id, ltrim(t.c.value('.', 'VARCHAR(2000)')) property
FROM (
    SELECT x = CAST('<t>' + 
        REPLACE(@prolist, ',', '</t><t>') + '</t>' AS XML)
) a
CROSS APPLY x.nodes('/t') t(c))  t2 on t1.id = t2.id and t1.property = t2.property
when not matched then INSERT (id,property)   
VALUES(t2.id, t2.property) 
when matched 
THEN UPDATE SET t1.id = t2.id
WHEN NOT MATCHED BY SOURCE THEN DELETE
; 
end

测试:

exec p_test 3, 'b,c'
select * from yourtable
exec p_test 3, 'a,b,c'
select * from yourtable
exec p_test 3, 'a,c'
select * from yourtable
exec p_test 4, 'g,h'
select * from yourtable

结果:

id  property
3   b
3   c

id  property
3   b
3   c
3   a

id  property
3   c
3   a

id  property
4   g
3   c
3   a
4   h

编辑:

为了更新新列,请使用此表:

create table yourtable (id int,property varchar(5), is_active bit default 1)

使用此程序:

alter procedure p_test
(
@id int, 
@prolist varchar(2000)
) as
begin
;with x as
(
  SELECT * FROM yourtable WHERE id = @ID
)
MERGE INTO 
x t1 
using 
(SELECT @id id, ltrim(t.c.value('.', 'VARCHAR(2000)')) property
FROM (
    SELECT x = CAST('<t>' + 
        REPLACE(@prolist, ',', '</t><t>') + '</t>' AS XML)
) a
CROSS APPLY x.nodes('/t') t(c))  t2 on t1.id = t2.id and t1.property = t2.property
when not matched then INSERT (id,property, is_active)   
VALUES(t2.id, t2.property, 1) 
when matched 
THEN UPDATE SET t1.id = t2.id, is_active = 1
WHEN NOT MATCHED BY SOURCE THEN 
UPDATE SET t1.is_active = 0
; 
end

答案 1 :(得分:1)

第一个:

insert into <tableName>(id, property) values(3, 'a');
insert into <tableName>(id, property) values(3, 'b');
insert into <tableName>(id, property) values(3, 'c');

第二期:

update <tableName> set property='ab' where property = 'a';
update <tableName> set property='bg' where property = 'c';
insert into <tableName>(id, property) values(3, 'ht');

现在,一个问题:你确定这是你的问题所需要的吗?通常,当我们调用列id时,我们希望它是标识符,即每行唯一。这可能有点偏离主题,但以防万一...

答案 2 :(得分:0)

应该有一个唯一的ID /主键。在该唯一字段的基础上提供任何唯一字段和更新记录。或者您可以使属性唯一或id和属性唯一。

答案 3 :(得分:0)

如果我理解得很好,你可以做一些类似的事情:

  Insert INTO @tempTable
  SELECT 3, * FROM dbo.splitstring('a,b,c,d')

它只是一个伪代码,您应该在存储过程中执行此操作。

如果这是正确的方法,你必须看一下:T-SQL split string