如何在sql中的动态查询中传递datetime?

时间:2015-04-03 05:13:31

标签: sql sql-server datetime

我写了一个像这样的存储过程

ALTER PROCEDURE [dbo].[spLoadPendingPaymentSheetByFilter] --'2015-04-01','2015-04-02','Select-One','Select-One','Select-One',''   
    @FromDate as datetime,
    @ToDate as datetime,
    @Status as nvarchar(50),
    @Remarks as nvarchar(50),
    @Paymenttype as nvarchar(50),
    @BillID as nvarchar(50)      
AS 
    Declare @Where as nvarchar(max)

    set @Where = '( MenifestDate BETWEEN  ''' +   CONVERT(VARCHAR(10),@FromDate, 101) + ''' and ''' + CONVERT(VARCHAR(10),@ToDate, 101) + ''' )'

    if(@Status <> 'Select-One')
       set @Where = 'Status = '+ @Status 

    if(@Remarks <> 'Select-One')
       set @Where = @Where + 'and Remarks = '+ @Remarks 

    if(@Paymenttype <> 'Select-One')
       set @Where = @Where + 'and PaymentType = ' + @Paymenttype 

    if(@BillID <> '')
       set @Where = @Where + 'and BillID = '+ @BillID 

    Declare @SelectString as nvarchar(1000)  
    set @SelectString = 'SELECT MasterID,BillID, MenifestDate, FarwardingNo,ReceverCountryName,Status,Remarks,PaymentType    
     FROM tblMenifest   
     WHERE ' + @Where

     exec @SelectString

当我执行它时出现此错误

  

名称&#39; SELECT MasterID,BillID,MenifestDate,FarwardingNo,ReceverCountryName,Status,Remarks,PaymentType FROM tblMenifest WHERE(MenifestDate BETWEEN&#39; 04/01 / 2015&#39;&#39; 04 / 02/2015&#39;)&#39;不是有效的标识符

MenifestDate列数据类型为datetime

1 个答案:

答案 0 :(得分:1)

我认为你想要EXEC(@SelectString)而不是exec @SelectString