0

I'm making a storet procedure that basicly just does 1 dynamic query with the result from another dynamic query as alias for 1 column. However, I get the following two errors (id doesn't say where):

  1. Incorrect syntax near '='.
  2. An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.

This is my code:

    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
4

2 回答 2

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

希望它可以帮助你

于 2013-07-08T07:46:08.563 回答
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...

使另一个错误也消失了:)

于 2013-07-08T14:02:20.127 回答