我有一个使用动态条件WHERE
子句查询的表。WHERE
当所有列都为空或某些列具有某些值时,我正在寻找一种获得简单条件的最佳方法。
我试过这样的事情:
SET @CONDITIONS = CASE
WHEN @VEHICLE_TYPE_NAME IS NULL
THEN ' ISNULL(A.VEHICLE_TYPE_NAME,'''') = ISNULL(A.VEHICLE_TYPE_NAME,'''') '
ELSE ' A.VEHICLE_TYPE_NAME = ''' + @VEHICLE_TYPE_NAME + ''''
END + ' ' + CASE
WHEN CAST(@PRODUCT_ID AS VARCHAR(MAX)) IS NULL
THEN ' AND ISNULL(A.PRODUCT_ID, ''-1'') = ISNULL(A.PRODUCT_ID, ''-1'') '
ELSE ' AND A.PRODUCT_ID = ''' + CAST(@PRODUCT_ID AS VARCHAR(MAX)) + ''''
END + ' ' + CASE
WHEN CAST(@CAPABILITY_ID AS VARCHAR(MAX)) IS NULL
THEN ' AND ISNULL(A.CAPABILITY_ID,''-1'') = ISNULL(A.CAPABILITY_ID,''-1'') '
ELSE ' AND A.CAPABILITY_ID = ''' + CAST(@CAPABILITY_ID AS VARCHAR(MAX)) + ''''
END + ' ' + CASE
WHEN @SPONSOR_FIRM_ID IS NULL
THEN ' AND ISNULL(A.SPONSOR_FIRM_ID,'''') = ISNULL(A.SPONSOR_FIRM_ID,'''') '
ELSE ' AND A.SPONSOR_FIRM_ID = ''' + @SPONSOR_FIRM_ID + ''''
END + ' ' + CASE
WHEN @CLIENT_FIRM_ID IS NULL
THEN ' AND ISNULL(A.CLIENT_FIRM_ID,'''') = ISNULL(A.CLIENT_FIRM_ID,'''') '
ELSE ' AND A.CLIENT_FIRM_ID = ''' + @CLIENT_FIRM_ID + ''''
END + ' ' + CASE
WHEN CAST(@DIST_PLATFORM_ID AS VARCHAR(MAX)) IS NULL
THEN ' AND ISNULL(A.DIST_PLATFORM_ID,''-1'') = ISNULL(A.DIST_PLATFORM_ID,''-1'') '
ELSE ' AND A.DIST_PLATFORM_ID = ''' + CAST(@DIST_PLATFORM_ID AS VARCHAR(MAX)) + ''''
END + ' ' + CASE
WHEN @RR_INTERNAL_NUMBER IS NULL
THEN 'AND ISNULL(A.RR_INTERNAL_NUMBER,'''') = ISNULL(A.RR_INTERNAL_NUMBER,'''') '
ELSE ' AND A.RR_INTERNAL_NUMBER = ''' + @RR_INTERNAL_NUMBER + ''''
END