Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 使用动态SQL插入语句,但不存在_Sql Server 2008_Tsql_Dynamic_Sql Insert_Not Exists - Fatal编程技术网

Sql server 2008 使用动态SQL插入语句,但不存在

Sql server 2008 使用动态SQL插入语句,但不存在,sql-server-2008,tsql,dynamic,sql-insert,not-exists,Sql Server 2008,Tsql,Dynamic,Sql Insert,Not Exists,我在SQLServer2008中的存储过程中有以下内容 declare @sql as varchar(max) set @sql='select col1,col2 from remote server' 我想做的是 insert into mytable(col1,col2) exec(@sql) Where not exists (select * from mytable where col1=?,col2=?) 这是行不通的。有什么解决办法吗。我的动态sql将保持原样,因为它使用o

我在SQLServer2008中的存储过程中有以下内容

declare @sql as varchar(max)
set @sql='select col1,col2 from remote server'
我想做的是

insert into mytable(col1,col2)
exec(@sql)
Where not exists
(select * from mytable where col1=?,col2=?)

这是行不通的。有什么解决办法吗。我的动态sql将保持原样,因为它使用openquery从某个远程服务器获取数据。所以我不知道;插入时,除了调用exec(@sql)之外,没有解决方案。还不确定如何使用Where not Exists子句中的“?”替换,因为数据来自动态SQL。

我对此进行了测试。它起作用了。别忘了授予权限

declare @sql as nvarchar(max)
set @sql='
insert [linkedserver].[database].[schema].[tablename] (col1, col2)
select @a, @b
where not exists (select 1 from [linkedserver].[database].[schema].[tablename]  
where col1 = @a and col2 = @b)
select * from [linkedserver].[database].[schema].[tablename]  
'

EXEC sp_executesql @sql, N'@a int, @b int', 1,4

如果你觉得以前的问题有帮助(或者是正确的),你应该接受这些问题的答案。