SQL - Where子句中的动态条件

时间:2017-08-29 15:35:02

标签: sql sql-server database

我有以下存储过程。我遇到的问题是“条件”参数。基本上每个条件都是它自己的列,所以它就像这样传递 -

@Conditions ='AND hcc_108 = 1 AND ...'等。

我正在尝试做这样的事情 -

ALTER PROC [dbo].[GetPatientPanelList] 
(
@CareProviderId int=null, 
@Patient nvarchar(60)=null, 
@Conditions varchar=null,
@LocationId int=null

) 

AS

if @Conditions is null

SELECT *
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
    ON t1.PatientID = t2.emr_id
WHERE
(t1.PreferredServiceLocationID = @LocationId OR @LocationId IS NULL)
AND (t1.CareProviderID = @CareProviderId OR @CareProviderId IS NULL)
AND (t1.FullName like '%' + @Patient + '%' OR @Patient IS NULL) 

else

SELECT *
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
    ON t1.PatientID = t2.emr_id
WHERE
(t1.PreferredServiceLocationID = @LocationId OR @LocationId IS NULL)
AND (t1.CareProviderID = @CareProviderId OR @CareProviderId IS NULL)
AND (t1.FullName like '%' + @Patient + '%' OR @Patient IS NULL)
+ @Conditions  

我只需要根据参数填充最后一个AND条件。我知道“+”是语法错误,但我似乎无法弄清楚如何实现这一点。

谢谢!

更新

我已经尝试过动态sql,但它一直说“命令已成功完成”

这是我目前的代码。我在一个单独的窗口中写这个,首先让查询工作。

DECLARE @where nvarchar(50) = ' and hcc_18 = 1'
,@sql nvarchar(MAX) ,
@CareProviderId int=null, 
@Patient nvarchar(60)=null,
@LocationId int=null

set @sql = 'select *
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
ON t1.PatientID = t2.emr_id
WHERE t1.PreferredServiceLocationID = IsNull('+ convert(varchar,@LocationId) +',t1.PreferredServiceLocationID)
AND (t1.CareProviderID = isnull(' + convert(varchar,@CareProviderId)+ ', t1.CareProviderID)
AND (t1.FullName like %' + @Patient + '% OR ' + @Patient + ' IS NULL)' + @where  

exec(@sql)

1 个答案:

答案 0 :(得分:1)

我修复了上次更新的语法问题。这应该有用......

DECLARE @where nvarchar(50) = ' and hcc_18 = 1'
,@sql nvarchar(MAX) ,
@CareProviderId int=null, 
@Patient nvarchar(60)=null,
@LocationId int=null

set @sql = 'select *
FROM vw_patient_attributes t1
INNER JOIN STG_OSHODS_DW.osh_rpt.dim_member_care_measures t2
ON t1.PatientID = t2.emr_id
WHERE t1.PreferredServiceLocationID = case when '+ convert(varchar(8),isnull(@LocationId,0)) +' = 0 then t1.PreferredServiceLocationID else ' + convert(varchar,isnull(@LocationId,0)) + ' end
AND (t1.CareProviderID = case when ' + convert(varchar,isnull(@CareProviderId,0)) + ' = 0 then t1.CareProviderID else ' + convert(varchar,isnull(@CareProviderId,0)) + ' end
AND (t1.FullName like ''%' + isnull(@Patient,'') + '%'' OR ' + isnull(@Patient,0) + '=0)' + @where  

print(@sql)
--exec(@sql)