动态替换列数据中的值?不工作

时间:2016-02-22 08:48:02

标签: sql sql-server

我想通过Updated_Attribute_Label_Name更新列Attribute_Label_Name,但是Updated_Attribute_Label_Name为null,则value应为Attribute_Label_Name

Click to see table

    IF EXISTS (
        SELECT *
        FROM #temp
        )
    DROP TABLE #temp

CREATE TABLE #temp (
    Attribute_Label_Name VARCHAR(1000)
    ,Updated_Attribute_Label_Name VARCHAR(1000)
    )

INSERT INTO #temp
SELECT Attribute_Label_Name
    ,Updated_Attribute_Label_Name
FROM Attribute_Label_With_Sku$

DECLARE @Attribute_Label_Name VARCHAR(1000)
    ,@Updated_Attribute_Label_Name VARCHAR(1000)

SET @Attribute_Label_Name = Attribute_Label_Name
    ,
SET @Updated_Attribute_Label_Name = Updated_Attribute_Label_Name

IF (@Updated_Attribute_Label_Name IS NOT NULL)
BEGIN
    UPDATE #temp
    SET @Attribute_Label_Name = @Updated_Attribute_Label_Name
END
ELSE
    (
            SELECT @Updated_Attribute_Label_Name = Updated_Attribute_Label_Name
            )

SELECT *
FROM #temp

2 个答案:

答案 0 :(得分:1)

似乎你没有设置这个值

SET @Attribute_Label_Name = Attribute_Label_Name
    ,
SET @Updated_Attribute_Label_Name = Updated_Attribute_Label_Name

你也可以单一选择

       select @Attribute_Label_Name =Attribute_Label_Name,
               @Updated_Attribute_Label_Name = Updated_Attribute_Label_Name
        from #temp

进一步请注意,如果您从#temp获得多个值,则可能无法获得预期结果

答案 1 :(得分:1)

UPDATE tablename 
SET Attribute_Label_Name=COALESCE(Updated_Attribute_Label_Name,Attribute_Label_Name)

COALESCE函数会先检查Updated_Attribute_Label_Name中的值是否为空,然后它会更新Attribute_Label_Name中的相同值。