SQL参数问题

时间:2017-12-28 14:25:09

标签: sql-server tsql

我有以下SQL查询。

DECLARE @OID NVARCHAR(MAX) = '(98,99,100,101,102,103,104,105)'

SELECT 
    Name = (SELECT [Name] 
            FROM Point 
            WHERE CAST(OID AS NVARCHAR(10)) = Point),
    Timestamp, 
    ValueNumeric
FROM 
    [IngeniousRPM_Bridge].[dbo].[Value] 
WHERE 
    CAST(Point AS NVARCHAR(10)) IN (98,99,100,101,102,103,104,105) 
    AND [Timestamp] BETWEEN '2017-11-01' AND '2017-11-30'  
    AND ValueNumeric IS NOT NULL

@OID为硬编码时,上述查询正常工作,但当我尝试传递@OID值时,如下所示,它不会返回表中的任何值。最后,我需要创建存储过程并传递@OID值。

DECLARE @OID NVARCHAR(MAX) = '(98,99,100,101,102,103,104,105)'

SELECT 
    Name = (SELECT [Name] 
            FROM Point 
            WHERE CAST(OID AS NVARCHAR(10)) = Point),
    Timestamp, 
    ValueNumeric
FROM 
    [IngeniousRPM_Bridge].[dbo].[Value] 
WHERE 
    CAST(Point AS NVARCHAR(10)) IN (@OID) 
    AND [Timestamp] BETWEEN '2017-11-01' AND '2017-11-30'  
    AND ValueNumeric IS NOT NULL

2 个答案:

答案 0 :(得分:0)

你需要做这样的事情

SELECT 98 OID, 'Test' OidTest, GETDATE() [TimeStamp]
INTO #MyTable

DECLARE @OID nvarchar(MAX)='98,99,100,101,102,103,104,105'
DECLARE @dyn nvarchar(MAX)

SELECT @dyn = 'SELECT * FROM #MyTable WHERE OID IN (' + @OID +') and [Timestamp] between  ''2017-11-01'' and  ''2017-12-30'''

exec (@dyn)

答案 1 :(得分:-2)

我目前无法添加评论......

如果从varchar字符串中删除括号,参数化版本是否有效?基本上你说“IN((98,99,100,101,102,103,104,105))”,我猜你想要的是“IN(98,99,100,101,102,103,104,105)”?

另外,我不会像建议的那样使用连接字符串,特别是如果你打算使用一个接受@OID值的存储过程......你会对SQL Injection漏洞开放。而是在存储过程中使用sp_executesql并传入参数。复制代码看起来像这样:

更新:已更新查询以包含日期参数。

declare @OID nvarchar(MAX)='98,99,100,101,102,103,104,105';
declare @sql nvarchar(max);
declare @startDate datetime;
declare @endDate datetime;
SET @sql = N'
            SELECT Name= (select [Name] from Point where CAST(OID AS 
            NVARCHAR(10)) 
            =Point),
            Timestamp, 
            ValueNumeric
            FROM [IngeniousRPM_Bridge].[dbo].[Value] where CAST(Point AS 
            NVARCHAR(10)) 
            In (' + @OID + ') and [Timestamp] between @startDateIN and 
            @endDateIN and 
            ValueNumeric is not null';
EXEC sp_executesql @sql
                   ,N'@startDateIN datetime, @endDateIN Datetime'
                   ,@startDateIN = @startDate
                   ,@endDateIN = @endDate;