-3

我正在尝试使用第一个表中的数据更新表。我正在尝试写这样的东西:

-- Create the temp tables
DROP TABLE #MyNewTable
CREATE TABLE #MyNewTable
    (
     UserId int IDENTITY(1, 1)
                NOT NULL,
     MarriedFlag bit NOT NULL
    )

DROP TABLE #MyOldTable
CREATE TABLE #MyOldTable
    (
     UserId int IDENTITY(1, 1)
                NOT NULL,
     Married nvarchar(50) NULL
    )

-- Insert test values
INSERT  INTO #MyOldTable
        ([Married])
VALUES  ('married'),
        ('married'),
        ('not married'),
        ('maybe married')
GO

-- First pass will do nothing as there is no data in #MyNewTable
UPDATE  #MyNewTable
SET     [MarriedFlag] = CASE I.[Married]
                          WHEN 'married' THEN 1
                          ELSE 0
                        END
FROM    [#MyOldTable] AS I,
        [#MyOldTable] AS O
WHERE   I.[UserId] = O.[UserId]

-- Will insert 4 values into #MyNewTable
SET IDENTITY_INSERT [#MyNewTable] ON

INSERT  INTO #MyNewTable
        ([UserId],
         [MarriedFlag])
        SELECT  I.[UserId],
                CASE I.[Married]
                  WHEN 'married' THEN 1
                  ELSE 0
                END
        FROM    [#MyOldTable] AS I
        WHERE   I.[UserId] NOT IN (SELECT   [UserId]
                                   FROM     [#MyNewTable])

SET IDENTITY_INSERT [#MyNewTable] OFF

SELECT  *
FROM    [#MyOldTable]

-- #MyOldTable Expected Output
UserId Married
1    married
2    married
3    not married
4    maybe married

SELECT  *
FROM    [#MyNewTable]

-- #MyNewTable Expected Output
UserId MarriedFlag
1    1
2    1
3    0
4    0

还有一点需要注意的是,这是触发器的一部分。这个想法是当旧表更新时,新值被清除,如果它们有效,则将其插入新表中。

4

2 回答 2

1

尝试这个。我想我知道你想做什么。这将创建一个带有 IsMarried 标志而不是描述性值的新表。

让我知道。

苹果电脑

 SELECT OLD.id
    ,   OLD.[Name]
    ,   CASE (OLD.MaritalStatus )
            WHEN 'Married' then 1
        ELSE
            0   
        END AS IsMarried
INTO dbo.newTable
FROM dbo.oldTable AS OLD

表格:

老的:

id  Name             MaritalStatus

1   Jack             Divorced  
2   Jill             Married   
3   James            Single    
4   Mark             Married   

新的:

id  Name           IsMarried

1   Jack           0
2   Jill           1
3   James          0
4   Mark           1
于 2012-04-21T07:20:26.683 回答
0

您没有加入任何内部/外部查询。如果您在派生表(id)中返回另一个字段并加入它,您会没事的。在添加额外的 id 字段之前,您需要结束您的 case 语句。

于 2012-04-20T23:52:41.407 回答