gpt4 book ai didi

sql - 如何使用表变量作为 OPENQUERY 的参数

转载 作者:行者123 更新时间:2023-12-04 15:44:25 28 4
gpt4 key购买 nike

如何使用表变量作为 OPENQUERY 的参数

就像是:

DECLARE @TSQL VARCHAR(8000)
DECLARE @VAR TABLE (VAR1 VARCHAR (2))
INSERT INTO @VAR values ('CA'),('OR') ,('WA')
SELECT @TSQL = 'SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + (SELECT VAR1 FROM @VAR)+ ''''''')'
EXEC (@TSQL)

最佳答案

我找到了一个适用于我的案例的解决方案:

DECLARE @query varchar(8000)
DECLARE @list VARCHAR(8000)
DECLARE @len int
SET @list = ''
DECLARE @var TABLE (var1 VARCHAR (30))
INSERT INTO @var values ('2015-01-01 00:00:00.000'),('2015-01-02 00:00:00.000') ,('2015-01-03 00:00:00.000')
SELECT @list = @list + ISNULL(var1 + ''''',''''', '')
FROM @var
SET @len = len(@list)
SET @list = ''''''+left(@list,@len-3)
SELECT @query =
'select *
FROM openquery([REMOTESERVER],
''
select *
from [DATABASE].[SCHEMA].[TABLE]
where FIELD in (' + @list + ')
'')'
EXEC (@query)

关于sql - 如何使用表变量作为 OPENQUERY 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31329026/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com