下面是我需要从不同数据库中获取同一段select语句的结果的代码片段。我已经使用光标从MASTER.dbo.sysdatabases中选择数据库列表,并将其传递给变量(即@name),该变量将一个接一个地保存数据库名称。
在select语句中,我传递的内容与@ name.dbo.currencyconversionrates
相同然而,在运行代码时,我没有得到结果。错误消息: -
Msg 102,Level 15,State 1,Line 23'。'。
附近的语法不正确
我的代码:
DECLARE @name nVARCHAR(100)
DECLARE @DBV nVARCHAR(100)
DECLARE @db_cursor CURSOR
SET @db_cursor = CURSOR FAST_FORWARD
FOR
SELECT name
FROM MASTER.dbo.sysdatabases
WHERE name IN ('ENT_Benteler','ENT_DEUTSCHE_BANK','ELV_Henry_Schein','ENT_HONDA')
OPEN @db_cursor
FETCH NEXT FROM @db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
set @DBV= @name
FETCH NEXT FROM @db_cursor INTO @name
--print @DBV
--use @name
select row_id, base_currency,conversion_currency, effective_period_start, effective_period_end, rate, effective_period_start as 'Use this for Script' from @name.dbo.currencyconversionrates
order by CONVERSION_CURRENCY,EFFECTIVE_PERIOD_START
END
CLOSE @db_cursor
DEALLOCATE @db_cursor
请纠正我的问题帮助我。
答案 0 :(得分:0)
select row_id, base_currency,conversion_currency, effective_period_start, effective_period_end, rate, effective_period_start as 'Use this for Script'
from @name.dbo.currencyconversionrates
order by CONVERSION_CURRENCY,EFFECTIVE_PERIOD_START
上述部分不正确,因为不支持from
之后的参数。您应该使用dynamic SQL
,忽略SQL injection
,您可以这样做:
DECLARE @SQL VARCHAR(MAX)
SET @SQL = '
select row_id, base_currency,conversion_currency, effective_period_start, effective_period_end, rate, effective_period_start as [Use this for Script]
from ['+ @name +'].dbo.currencyconversionrates
order by CONVERSION_CURRENCY,EFFECTIVE_PERIOD_START'
print (@SQL)
--EXEC (@SQL)
在print
EXEC