如果该表中的数据不存在,我正在从表中选择数据并将其插入到另一个表中。
DECLARE @EmployeeNumber NVARCHAR(100)
SET @EmployeeNumber = 'Emp001'
IF EXISTS(SELECT E.EmployeeNumber FROM [databaseOne].[dbo].[Employee] E WHERE E.EmployeeNumber = @EmployeeNumber)
BEGIN
IF NOT EXISTS(SELECT UT.EmployeeNumber FROM UserTable UT WHERE UT.EmployeeNumber = @EmployeeNumber)
BEGIN
INSERT INTO UserTable(EmployeeNumber, Surname)
SELECT E.EmployeeNumber, E.Surname FROM [databaseOne].[dbo].[Employee] E
WHERE E.EmployeeNumber = @EmployeeNumber
END
ELSE
BEGIN
--Update
END
END
如果数据确实存在,我只想更新现有数据。
如何更新而不是INSERT INTO。
亲切的问候
答案 0 :(得分:3)
您应该使用Merge
功能。
您的查询看起来有点像这样:
MERGE UserTable AS Target
USING (SELECT E.EmployeeNumber, E.Surname FROM [databaseOne].[dbo].[Employee] E
WHERE EmployeeNumber = @EmployeeNumber) AS Source
ON Target.EmployeeNumber = Source.EmployeeNumber
WHEN MATHCED THEN
UPDATE SET Target.Surname = Source.Surname
WHEN NOT MATCHED THEN
INSERT (EmployeeNumber, Surname) VALUES (Source.EmployeeNumber,Source.Surname);
参考here。
答案 1 :(得分:1)
尝试以下方面的内容:
UPDATE UserTable
SET
EmployeeNumber=E.EmployeeNumber
Surname=E.Surname
FROM UserTable
INNER JOIN [databaseOne].[dbo].[Employee] AS E
ON (E.EmployeeNumber = UserTable.EmployeeNumber )
WHERE UserTable.EmployeeNumber = @EmployeeNumber