我正在使用sql OPENQUERY
检查记录是否存在通过参数更新它,如果没有插入新记录。
这是我到目前为止所拥有的
DECLARE @sql VARCHAR (8000)
DECLARE @Id VARCHAR(20)
SET @Id= '31124'
SET @sql = '
SELECT * FROM OPENQUERY
(
SERVERNAME,
''
SELECT Name FROM table WHERE Id= ''''' + @Id + '''''
''
)'
EXEC (@sql)
答案 0 :(得分:2)
DECLARE @sql VARCHAR (8000)
DECLARE @Id VARCHAR(20)
SELECT @Id= '31124'
SELECT @sql =
'
IF EXISTS
(
SELECT * FROM OPENQUERY
(
SERVERNAME,
''SELECT Name FROM table WHERE Id= ''''' + @Id + '''''''
)
)
BEGIN
UPDATE OPENQUERY
(
SERVERNAME,
''SELECT Name FROM table WHERE Id= ''''' + @Id + '''''''
)
SET Name = ''NewName''
ELSE
INSERT OPENQUERY
(
SERVERNAME,
''SELECT Name FROM table''
)
VALUES
(
''NewName''
)
END
'
EXEC (@sql)
除非您有特定要求使用EXEC
,否则您不需要它。
DECLARE @Id VARCHAR(20)
SELECT @Id= '31124'
IF EXISTS
(
SELECT * FROM OPENQUERY
(
SERVERNAME,
'SELECT Name FROM table WHERE Id= ''' + @Id + ''''
)
)
BEGIN
UPDATE OPENQUERY
(
SERVERNAME,
'SELECT Name FROM table WHERE Id= ''' + @Id + ''''
)
SET Name = 'NewName'
ELSE
INSERT OPENQUERY
(
SERVERNAME,
'SELECT Name FROM table'
)
VALUES
(
'NewName'
)
END