我正在尝试使用第一个表中的数据更新表。我正在尝试写这样的东西:
-- 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
需要注意的是,这是触发器的一部分。我们的想法是更新旧表时,清除新值,如果它们有效,则将其插入新表中。
答案 0 :(得分:1)
试试这个。我想我知道你想做什么。这将创建一个带有IsMarried标志而不是描述性值的新表。
让我知道。
MAC
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
TABLES:
OLD:
id Name MaritalStatus
1 Jack Divorced
2 Jill Married
3 James Single
4 Mark Married
NEW:
id Name IsMarried
1 Jack 0
2 Jill 1
3 James 0
4 Mark 1
答案 1 :(得分:0)
您没有使用内部/外部查询加入任何内容。如果你在派生表中返回另一个字段(id)并加入它就可以了。在添加额外的id字段之前,您需要结束case语句。