一次更新多个值

时间:2018-05-04 05:50:21

标签: sql sql-server

这是我的示例数据

   APSDEV      clusterData       Stylecolor
     1            0012             3456
     2            0013             4567

和更新查询

UPDATE <table name> SET  APS_Dev = 1 FROM <table_name> WHERE d.Style_Color = 0012 AND Cluster_ID = 3456  

UPDATE <table name> SET  APS_Dev = 2 FROM <table_name> WHERE d.Style_Color = 0013 AND Cluster_ID = 4567 

我想要更新查询

  UPDATE <table name>

  SET  APS_Dev = (select          
             (SELECT Item  FROM  fn_split(Dataval,':') where idx in (1))
                from @test)                                              
   FROM <table_name>
   WHERE d.Style_Color in (select 
                 (SELECT Item  FROM  fn_split(Dataval,':') where idx in (3))                            
                           from @test)          

    AND Cluster_ID in     (select 
                  (SELECT Item  FROM  fn_split(Dataval,':')where idx in (2)) 
                            from @test)

获取错误:

  

子查询返回的值超过1。这是不允许的        子查询跟随=,!=,&lt;,&lt; =,&gt;,&gt; =或当子查询用作        表达

我理解错误是由于APS_Dev“=”符号。任何人都可以建议如何声明值

2 个答案:

答案 0 :(得分:0)

不确定我是否完全理解您要尝试实现的目标,但如果您拆分DataVal并将其推入临时表的列中,则可以根据多条件where子句更新主表。

DECLARE @test TABLE (APSDEV INT
                    ,clusterData NVARCHAR(4)
                    ,stylecolor INT
                    )
DECLARE @toUpdate TABLE (Field1 INT
                        ,Field2 INT
                        ,Field3 INT
                        ,APSDEV INT
                        ,clusterData NVARCHAR(4)
                        ,stylecolor INT
                        )
INSERT  INTO @test
VALUES  (1, '0012', 3456),
        (2, '0013', 4567)
SELECT  *
FROM    @test

INSERT  INTO @toUpdate
VALUES  (1, 1, 1, NULL, '0012', 3456),
        (2, 2, 2, NULL, '0013', 4567)

SELECT  *
FROM    @toUpdate

UPDATE  @toUpdate
SET     APSDEV = [@test].APSDEV
FROM    @toUpdate
JOIN    @test ON [@test].clusterData = [@toUpdate].clusterData
                 AND [@test].stylecolor = [@toUpdate].stylecolor

SELECT  *
FROM    @toUpdate

如果我错过了你想要达到的目的,请告诉我。

答案 1 :(得分:0)

你可以试试这个。

UPDATE T
    SET APS_Dev = [1]
FROM 
    TheTable T
    INNER JOIN ( 
        SELECT * FROM @test
        CROSS APPLY fn_split(Dataval,':') PIVOT (MAX(Item) FOR idx IN ([1],[2],[3])) ) F
        ON Style_Color = [2]
            AND Cluster_ID = [3]