我正在尝试使用第一个表中的数据更新表。我正在尝试写这样的东西:
-- 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
还有一点需要注意的是,这是触发器的一部分。这个想法是当旧表更新时,新值被清除,如果它们有效,则将其插入新表中。