“BETWEEN”和“IN”运算符的SQL参数化查询无法正常工作

时间:2014-09-05 13:57:01

标签: sql parameterized-query

SELECT top 10 * 
  FRPM Events  
    WHERE (StartDayID between @p0 
             AND BusinessEventCode in @p1),
       N'@p0 nvarchar(4000),@p1 nvarchar(4000)',@p0=N'20110701 
           and 20140724',@p1=N'HighVoltage,LowVoltage'

StartDayID是整数,BusinessEventCodenvarchar列。

BETWEENIN运营商上没有在互联网上找到任何帮助..

3 个答案:

答案 0 :(得分:0)

更改查询中的条件,如下所示:

...where (StartDayID between @p0 and @p1) AND BusinessEventCode in (@p2);

@p0 = 20110701
@p1 = 20140724
@p2 = HighVoltage,LowVoltage'

答案 1 :(得分:0)

正如我在评论中指出的那样,你可以做

WHERE (StartDayID between @p0 

您的查询的一部分,将@ p0拆分为两个变量:

declare @startDate datetime
declare @endDate datetime

select @startdate = 20110701, @endDate = 20140724
....
WHERE (StartDayID between @startDate and @endDate) 

查询的IN部分有点棘手,您可能需要将各个值拆分为临时/变量表,以便在IN语句中处理它们。

您可以使用拆分功能执行此操作,例如(取自http://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql/):

CREATE FUNCTION [dbo].[Split]
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE 
AS
RETURN 
(
    WITH Split(stpos,endpos) 
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split
)
GO

然后在您的查询中:

....
AND BusinessEventCode in @p1),

这会变成:

@p1=N'HighVoltage,LowVoltage'

....
AND BusinessEventCode in (SELECT Data FROM dbo.Split(@p1, ','))),

请注意,如果采用此路线,您可能需要重新考虑分隔符,因为","在文本中很常见,管道(|)之类的东西可能不太常见。

答案 2 :(得分:0)

如果必须使用这些参数,可以使用动态SQL。这不是我的第一个建议,但根据您的使用情况可能是可行的。

declare @p0 nvarchar(100)=N'20110701 and 20140724';
declare @p1 nvarchar(100)=N'''HighVoltage'',''LowVoltage''';
declare @SQL nvarchar(Max);

set @SQL = 'SELECT TOP 10 * '+
    'FROM Events '+
        'WHERE StartDayID between '+ @p0 + 
        ' AND BusinessEventCode IN(' + @p1 + ')'

exec sp_executesql @SQL