exec语句中的简单SQL不接受exec内提取的数据库名称

时间:2014-04-30 14:35:16

标签: sql exec

我有以下exec语句,当我用@DBName替换Use [HUM_FM_1_SYNTQ_TEST]时,我得到一个错误数据库' @ DBName'不存在。我尝试了['' + @ DBName +'']并得到类似的错误。我做错了什么?

非常感谢任何帮助。感谢

exec(' 
-- Get position number and dbname
DECLARE @posNo bigint
DECLARE @DBName nvarchar(100)
DECLARE @sampleDate nvarchar (30)
DECLARE @sampleTime nvarchar (30)
DECLARE @runID bigint

Set @posNo = (select PositionNumber from ' + @temp_table_distincts_withPositions + 
' where [COutputData_3_Segment_Number] = ' + @segment_no + ')
Set @DBName = (select DBName from ' + @temp_table_distincts_withPositions + 
' where [COutputData_3_Segment_Number] = ' + @segment_no + ')
Set @runID = (select RunID from ' + @temp_table_distincts_withPositions + 
' where [COutputData_3_Segment_Number] = ' + @segment_no + ')

select @runID

-- Query the appropriate seriesvariables table

-- Get Sample Date
Use [HUM_FM_1_SYNTQ_TEST]
Set @sampleDate = (Select seriesvariables_value from
(
select *, row_number() over 
(order by SeriesVariables_ID asc) as rownum from Seriesvariables where 
SeriesVariables_Label = ''Enter Tablet Segment Pull Date'' and
Series_ID = @runID) as tbl1 
where rownum = @posNo)

select @sampleDate

' )

1 个答案:

答案 0 :(得分:1)

@DBName是动态SQL字符串中的变量,而不是表的直接标识符,因此您不能直接在USE语句中使用它,也不能将其转换为相同动态级别的标准标识符SQL。

我认为在没有一些彻底重组的情况下做你想做的事情的唯一方法(我无法帮助你,因为我不知道更大的场景是什么)是使用双重动态SQL - 在换句话说,使用动态SQL创建一个随后执行的SQL字符串。

这是一个坏主意(它令人困惑且难以维护),所以我建议花点时间看看你是否可以重组这个问题。