如何将表值参数与IN关键字一起使用

时间:2018-01-17 01:06:57

标签: sql-server stored-procedures table-valued-parameters

编辑:

我试图替换:

@LocationIDs NVARCHAR(MAX) = null,

@LocationIDs LocationIdArray READONLY,

但现在我收到一条错误说:

  

必须声明标量变量" @ LocationIDs"。

- 结束编辑 -

我有这个存储过程需要解决:

CREATE PROCEDURE [dbo].[spAP_GetTechnician_Door_Unlock]   
    @LocationIDs NVARCHAR(MAX) = NULL,  
    @AlarmDateFrom DATETIME = NULL,  
    @AlarmDateTo DATETIME = NULL,  
    @TechnicianID INT = NULL,
    @LocationId INT = NULL
AS
BEGIN
    IF (@LocationIDs = 'x')  
    BEGIN
        SELECT @LocationIDs = dbo.fn_GetAll_Location_Id()  
    END

    DECLARE @query NVARCHAR(MAX);

    SET @query = 'WITH CTE AS (SELECT ROW_NUMBER() OVER(ORDER BY al.Alarm_Log_ID desc)AS RowNumber,  
 isnull(t.Technician_ID,'''')[Technician_ID], (isnull(t.Last_Name,'''') +'' ''+  isnull(t.Name,''''))  TechnicianName,isnull(t.Emailid,'''') as EmailID,isnull(t.phone,'''') as Phone,dbo.fNAP_DateFormat(al.Alarm_date) as Alarm_date,                  
 Al.Site_ID,s.Name as SiteName,al.point_Address,l.location_Name,l.Location_ID ,shs.StatusData                  
from z_EntityMast_Alarm_Log al                   
left join  z_EntityMast_Technician t on al.Technician_ID=t.Technician_id                  
left join z_EntityMast_Site s on s.Site_ID=al.Site_ID                  
left join z_EntityMast_Location l on s.Location_ID=l.Location_id                  
left join z_EntityMast_Site_Hardware_Status shs on s.site_id=shs.siteid                   
left join z_SysVar_Alarm_Type_00004 at on al.Alarm_Type=at.ID                   
where at.Is_Linkable=1 and al.Alarm_Type !=70'               
if(isnull(@LocationId,0)!=0)            
set @query=@query+' and s.Location_ID ='+convert(varchar(12),@LocationId);            
else            
set @query=@query+' and s.Location_ID in ('+@LocationIDs+')';   
if(isnull(@AlarmDateFrom,0)!=0 and @AlarmDateFrom !='')  
set @query=@query+'and (DATEDIFF(DAY,'''+convert(varchar(30),@AlarmDateFrom)+''', al.Alarm_Date)>=0 and  DATEDIFF(DAY,'''+convert(varchar(30),@AlarmDateTo)+''',al.Alarm_Date)<=0)';                
if(isnull(@TechnicianID,0)!=0)  
set @query=@query+'and t.Technician_ID ='+ convert(varchar(10),@TechnicianID);  
set @query=@query + ')';  
set @query=@query +'select * from CTE ';  

    -- PRINT @query  
    EXEC (@query)  
END

我需要对其进行优化,我必须对LocationIds参数使用表值参数,而不是使用NVARCHAR(MAX)

问题在于这行代码:

SET @query  = @query + ' and s.Location_ID in ('+@LocationIDs+')';   

我的问题是:如何替换该行代码并将其替换为表值参数,以便连接仍然有效?

谢谢!

1 个答案:

答案 0 :(得分:1)

  

SET @query = @query + ' and s.Location_ID in ('+@LocationIDs+')';
  我的问题是:如何替换该行代码并替换它   用一个表值参数以这种方式连接   还能用吗?

假设您的LocationIdArray有此定义:

create type LocationIdArray as table (LocationId int);

然后你的IN应该是这样的:

and s.Location_ID in (select LocationId from @LocationIDs)

这不会在exec内工作,因为@LocationID位于exec的外部范围内,您可以将其作为参数传递给sp_executesql但是您可以做的最好的事情是将动态查询重写为静态查询,因为这里没有理由使用动态代码。