我正在制作一个storet过程,基本上只进行1次动态查询,其中另一个动态查询的结果为1列的别名。 但是,我得到以下两个错误(id没有说明在哪里):
这是我的代码:
ALTER PROCEDURE myProcedure
@param1 NVARCHAR(50),
@param2 NVARCHAR(50),
@param3 int
AS
BEGIN
DECLARE @query Nvarchar(2000)
DECLARE @columnName Nvarchar(250)
DECLARE @columnNameOUT Nvarchar(250)
set @columnName = ''
SELECT @query = 'SELECT (@columnNameOUT = CONVERT(time(0), TimeStamps."timeStamp", 108)) AS alias FROM TimeStamps WHERE [param3] = ''' + CAST(@param3 AS VARCHAR) + ''' AND param2 = ''' + @param2 + ''' AND [param1] = ''' + @param1 +''''
EXECUTE sp_executesql @query, N'@columnNameOUT NVARCHAR(30) OUTPUT', @columnNameOUT = @columnName OUTPUT
set @query = ''
IF @param1 IS NULL
BEGIN
SELECT @query = 'SELECT column1 AS '''+@columnName+''', column2, column3 ETA FROM myTable WHERE [param3] = '''+CAST(@param3 AS VARCHAR) +''' AND param2 = '''+@param2+''' AND [param1] IS NULL order by column1'
END
ELSE
BEGIN
SELECT @query = 'SELECT column1 AS '''+@columnName+''', column2, column3 ETA FROM myTable WHERE [param3] = '''+CAST(@param3 AS VARCHAR) +''' AND param2 = '''+@param2+''' AND [param1] ) '''+@param1+''' order by column1'
END
EXEC(@query);
END
答案 0 :(得分:1)
首先,支架存在问题:
' AND [param1] ) '
你的第二个问题出在ELSE声明中(有一个解决方案):
BEGIN
SELECT @query = 'SELECT column1, column2, column3 ETA
FROM myTable
WHERE [param3] = '''+CAST(@param3 AS VARCHAR) +'''
AND [param2] = '''+@param2+'''
AND [param1] = '''+@param1+''' order by column1';
END
但第一个问题看起来像这里,但不知道如何解决它:
SELECT @query = 'SELECT (@columnNameOUT = CONVERT(time(0), TimeStamps."timeStamp", 108)) AS alias
希望它可以帮到你
答案 1 :(得分:0)
终于自己解决了!
原来这个小查询:
SELECT @query = 'SELECT (@columnNameOUT = CONVERT(time(0), TimeStamps."timeStamp", 108)) AS alias FROM TimeStamps WHERE [param3] = ''' + CAST(@param3 AS VARCHAR) + ''' AND param2 = ''' + @param2 + ''' AND [param1] = ''' + @param1 +''''
有机会回归空虚。所以在添加了IF @columnName = ''
之后,一切都解决了。
改变这一行:
... 'SELECT (@columnNameOUT = CONVERT(time(0), TimeStamps."timeStamp", 108)) AS alias FROM ...
对此:
...'SELECT @columnNameOUT = CONVERT(time(0), TimeStamps."timeStamp", 108) FROM...
使另一个错误也消失了:)