动态查询中的select语句中的空格

时间:2011-09-01 08:16:17

标签: sql sql-server-2008

我有一个像这样的动态查询:

SET @str_Query = 'SELECT SIM.Item_ID,
                  SIM.Item_Description,
                  SU.Short_Description AS Unit,
                  SIM.Std_Lead_Time,'+
                  '' ''+' AS Last_Purchase_Rate
                  FROM  FKMS_Item_Master AS SIM
                        INNER JOIN FKMS_STP_Units SU
                        ON SIM.Item_Purchase_Unit=SU.Unit_Id' +
                 ' WHERE ' + @str_Condition + 
                            ' AND SIM.Location_Id =' + CAST(@aint_Location_Id AS VARCHAR(10)) +
                            ' AND SIM.Item_Deleted =0 
                              AND SIM.Approved_On IS NOT NULL'  
                +' ORDER BY SIM.Item_Description'   

我想将空格检索为Last_Purchase_Rate

在'''''AS Last_Purchase_Rate的部分显示语法错误 当我执行此查询时。 如果我打印此动态查询,查询似乎是正确的。它在AS之前显示为具有空格的AS Last_Purchase_Rate。请帮忙。

4 个答案:

答案 0 :(得分:2)

我会写

...SIM.Std_Lead_Time, '' '' AS Last_Purchase_Rate...

而不是

...SIM.Std_Lead_Time,'+'' ''+' AS Last_Purchase_Rate...

答案 1 :(得分:1)

你没有逃脱所有引用。

您的陈述的工作版本将是

SET @str_Query = 'SELECT SIM.Item_ID,
                  SIM.Item_Description,
                  SU.Short_Description AS Unit,
                  SIM.Std_Lead_Time,'
                  + ''' '''
                  + ' AS Last_Purchase_Rate
                  FROM  FKMS_Item_Master AS SIM
                        INNER JOIN FKMS_STP_Units SU
                        ON SIM.Item_Purchase_Unit=SU.Unit_Id' +
                 ' WHERE ' + @str_Condition + 
                            ' AND SIM.Location_Id =' + CAST(@aint_Location_Id AS VARCHAR(10)) +
                            ' AND SIM.Item_Deleted =0 
                              AND SIM.Approved_On IS NOT NULL'  
                +' ORDER BY SIM.Item_Description'   

但我发现通过稍微重新格式化,错误更容易发现

SET @str_Query = 
    'SELECT SIM.Item_ID '
    + ', SIM.Item_Description '
    + ', SU.Short_Description AS Unit '
    + ', SIM.Std_Lead_Time '
    + ', '' ''' + ' AS Last_Purchase_Rate '
    + 'FROM  FKMS_Item_Master AS SIM '
    + '      INNER JOIN FKMS_STP_Units SU '
    + '                   ON SIM.Item_Purchase_Unit=SU.Unit_Id ' 
    + ' WHERE ' + @str_Condition 
    + '       AND SIM.Location_Id = ' + CAST(@aint_Location_Id AS VARCHAR(10)) 
    + '       AND SIM.Item_Deleted =0 '
    + '       AND SIM.Approved_On IS NOT NULL '  
    + ' ORDER BY SIM.Item_Description '   

答案 2 :(得分:1)

为什么不使用NULL而不是空格然后在你的应用程序中处理结果?

即,

SET @str_Query = 'SELECT SIM.Item_ID,
              SIM.Item_Description,
              SU.Short_Description AS Unit,
              SIM.Std_Lead_Time,
              NULL AS Last_Purchase_Rate, -- and so on.

你也可以使用CHAR(32):

SET @str_Query = 'SELECT SIM.Item_ID,
              SIM.Item_Description,
              SU.Short_Description AS Unit,
              SIM.Std_Lead_Time,
              CHAR(32) AS Last_Purchase_Rate, -- and so on.

答案 3 :(得分:0)

尝试使用tsql函数SPACE(1)