存储过程操作数类型冲突:日期与int不兼容

时间:2016-07-21 13:32:29

标签: sql sql-server stored-procedures

这是我的存储过程

text-transform: capitalize;

命令成功完成。

但是当我用该参数执行该存储过程时

ALTER PROCEDURE [dbo].[sp_ListFirmJobFilter]
    (@Status as nvarchar(10),
     @CityID as nvarchar(10),
     @DataStart as date,
     @DataEnd as date,
     @FirmID as nvarchar(10)
)
AS
BEGIN
    DECLARE @Sql NVARCHAR(MAX) 
    SET @Sql = N'SELECT * FROM Jobs WHERE 1=1'

    IF @Status IS NOT NULL
    BEGIN
        SET @Sql += ' AND Status = '+@Status+''
    END

    IF @CityID IS NOT NULL
    BEGIN
        SET @Sql += ' AND CityID = '+@CityID+''
    END

    IF @FirmID IS NOT NULL
    BEGIN
        SET @Sql += ' AND FirmID = '+@FirmID+' '
    END

    IF @DataStart IS NOT NULL
    BEGIN
        SET @Sql += ' AND (InsertedDate >= ' + CONVERT(VARCHAR(50), @DataStart)
        SET @Sql += ' AND InsertedDate <= ' + CONVERT(VARCHAR(50), @DataEnd)
        SET @Sql += ')'
    END 

    PRINT(@Sql)
    EXEC(@Sql)
END

我收到错误:

  

操作数类型冲突:日期与int

不兼容

我查找已执行的SQL命令(Print SQL string)。这是执行命令:

DECLARE @return_value int

EXEC @return_value = [dbo].[sp_ListFirmJobFilter]
                        @Status = NULL,
                        @CityID = null,
                        @DataStart = N'2016-06-26',
                        @DataEnd = N'2016-06-28',
                        @FirmID = 4

SELECT  'Return Value' = @return_value
GO

当我执行它时会出现同样的错误。我改成了:

SELECT * 
FROM Jobs 
WHERE 1=1 
  AND FirmID = 4  
  AND (InsertedDate >= 2016-06-26 AND InsertedDate <= 2016-06-28)

这很有效。

我该怎么办? SELECT * FROM Jobs WHERE 1=1 AND FirmID = 4 AND (InsertedDate >= '2016-06-26' AND InsertedDate <= '2016-06-28') 类型为日期

3 个答案:

答案 0 :(得分:1)

用单引号包裹日期

SET @Sql += ' AND (InsertedDate >= ''' + CONVERT(VARCHAR(50), @DataStart) +''''
SET @Sql += ' AND InsertedDate <= ''' + CONVERT(VARCHAR(50), @DataEnd) +''''
SET @Sql += ')'

答案 1 :(得分:1)

正如Squirrel所提到的,你自己也注意到了,日期必须用单引号括起来。

就我个人而言,我喜欢使用QUOTENAME

SET @Sql += ' AND InsertedDate <= ' + QUOTENAME(CONVERT(VARCHAR(50), @DataEnd), '''')

答案 2 :(得分:0)

您需要将日期字符串括在单引号中

SET @Sql += ' AND (InsertedDate >= ==' + CONVERT(VARCHAR(50), @DataStart) + ''''