【问题标题】:Insert Statement with Dynamic SQL and Where NOT EXISTS使用动态 SQL 和 Where NOT EXISTS 插入语句
【发布时间】:2013-10-30 22:43:12
【问题描述】:

我在 SQL Server 2008 中的存储过程中有以下内容

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。

【问题讨论】:

  • 如果您认为以前的问题有帮助(或者它们是正确的),您应该接受它们的答案。

标签: sql-server-2008 tsql dynamic sql-insert not-exists


【解决方案1】:

我对此进行了测试。有用。不要忘记授予权限。

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

【讨论】:

    猜你喜欢
    • 2013-04-17
    • 2018-01-28
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2012-05-16
    • 2012-11-03
    • 2018-01-08
    • 2016-01-09
    相关资源
    最近更新 更多