编写动态SQL查询时出错

时间:2017-01-12 08:27:10

标签: sql

我需要像这样的动态查询sp,

declare @query nvarchar(max)='
declare @DateParam datetime
set @DateParam=getdate()
select * from tblOrders
where Order_site='TSN' 
AND CAST(ORDER_APPROVED_DATE_LT AS DATE)=CAST(GETDATE() AS DATE)'

这样写的时候,我收到了TSN'的报价部分。它不允许单引号。我怎样才能达到where条件?

4 个答案:

答案 0 :(得分:2)

您需要将其构建为字符串。

declare @query nvarchar(max)='
declare @DateParam datetime
set @DateParam=getdate()
select * from tblOrders
where Order_site=''TSN'' 
AND CAST(ORDER_APPROVED_DATE_LT AS DATE)=CAST(GETDATE() AS DATE)'

答案 1 :(得分:1)

问题是因为' TSN'你正在破坏你的主要nvarchar,试试这样

declare @query nvarchar(max)='

declare @DateParam datetime
set @DateParam=getdate()

select * from tblOrders
where Order_site=' + 'TSN' + 
'AND CAST(ORDER_APPROVED_DATE_LT AS DATE)=CAST(GETDATE() AS DATE)'

答案 2 :(得分:1)

如果你在存储过程中使用动态sql尝试这样的事情。最好为主选择查询和动态使用不同的变量,其中查询可以很容易地扩展。使用这种方法,当proc变得冗长时,它将很容易维护

        declare @finalquery varchar(max)
        declare @mainSelectquery nvarchar(500);
        declare @whereCondtions varchar (1000);
        declare @DateParam datetime
        set @mainSelectquery=''
        set @whereCondtions =''

        set @finalquery =''

        set @DateParam=getdate()
        set @mainSelectquery = 'select * from tblOrders  where 1=1  '

        set @whereCondtions =  ' and Order_site =''TSN'''

        set @whereCondtions = @whereCondtions + ' AND CAST(ORDER_APPROVED_DATE_LT AS DATE)=CAST(GETDATE() AS DATE)' 

        set @finalquery =( @mainSelectquery + @whereCondtions)

        print @finalquery

     ---- You can further extend this by adding more where condition based on the parameter pass in stored proc 
  if (@OrderID !=0)
  begin 
     set @whereCondtions =  ' OrderID='+str ( @stateRefID )
  end

答案 3 :(得分:1)

作为使用双引号转义字符串的替代方法,您可以尝试使用QUOTENAME()

declare @val nvarchar(max) = 'TSN'

declare @query nvarchar(max)='
declare @DateParam datetime
set @DateParam=getdate()
select * from tblOrders
where Order_site= ' + quotename(@val, '''') + 
' AND CAST(ORDER_APPROVED_DATE_LT AS DATE)=CAST(GETDATE() AS DATE)'

select @query