我有一个数据类型问题。以下代码行适用于我们的数据库:
WHERE e_ru IN (5420,5410,5550,6230,6240,6250)
现在我想为每个月e_ru
插入一组不同的数字。
DECLARE @StartDate DATETIME, @EndDate DATETIME, @MonthOfYear TINYINT, @RUsToAudit NVARCHAR
SET @StartDate = (dateadd(month, datediff(month, 0, DATEADD(month, -6, GETDATE())),0)+15)
SET @EndDate = (dateadd(month, datediff(month, 0, DATEADD(month, 0, GETDATE())),0)+14)
SET @MonthOfYear = DATEPART(month, GETDATE())
SET @RUsToAudit =
CASE
WHEN @MonthOfYear = 1 THEN (SELECT 5420,5410,5550,6230,6240,6250)
WHEN @MonthOfYear = 2 THEN (SELECT 5420,5410,5550,6230,6240,6250)
WHEN @MonthOfYear = 3 THEN (SELECT 5420,5410,5550,6230,6240,6250)
WHEN @MonthOfYear = 4 THEN (SELECT 5460,5470,5500)
WHEN @MonthOfYear = 5 THEN (SELECT 5420,5410,5550,6230,6240,6250)
WHEN @MonthOfYear = 6 THEN (SELECT 5530,5910)
WHEN @MonthOfYear = 7 THEN (SELECT 5420,5410,5550,6230,6240,6250)
WHEN @MonthOfYear = 8 THEN (SELECT 5420,5410,5550,6230,6240,6250)
WHEN @MonthOfYear = 9 THEN (SELECT 5460,5470,5500)
WHEN @MonthOfYear = 10 THEN (SELECT 5420,5410,5550,6230,6240,6250)
WHEN @MonthOfYear = 11 THEN (SELECT 5530,5910)
WHEN @MonthOfYear = 12 THEN (SELECT 5420,5410,5550,6230,6240,6250)
END
SELECT @StartDate AS 'Report Start Date', @EndDate AS 'Report End Date', @MonthOfYear AS 'Month', @RUsToAudit AS 'Programs'
答案 0 :(得分:1)
我建议您在数据库中创建一个永久表来存储此信息。具体来说,是一个带有MonthNumber和ListItem(都是整数)的表,然后使用Hogan建议的查询。
在我看来,好像您(当前)将业务规则硬编码到数据库中。通过将这些值分隔到另一个表中,您可以通过更改表中的数据而不是潜入代码来轻松更改功能,以进行更改。
这可能需要一些时间来设置,但从长远来看,它将是一个更优雅的解决方案(随着业务流程的变化)。
答案 1 :(得分:0)
例如,这可行,但可能不是您想要的 - 我需要知道您要做的是如何制作正确的数据模型
WITH dataTable AS
(
SELECT 1 AS Month, '5420,5410,5550,6230,6240,6250' AS List
UNION ALL
SELECT 2 AS Month, '5420,5410,5550,6230,6240,6250' AS List
UNION ALL
SELECT 3 AS Month, '5420,5410,5550,6230,6240,6250' AS List
UNION ALL
SELECT 4 AS Month, '5460,5470,5500' AS List
UNION ALL
SELECT 5 AS Month, '5420,5410,5550,6230,6240,6250' AS List
UNION ALL
SELECT 6 AS Month, '5530,5910' AS List
UNION ALL
SELECT 7 AS Month, '5420,5410,5550,6230,6240,6250' AS List
UNION ALL
SELECT 8 AS Month, '5420,5410,5550,6230,6240,6250' AS List
UNION ALL
SELECT 9 AS Month, '5460,5470,5500' AS List
UNION ALL
SELECT 10 AS Month, '5420,5410,5550,6230,6240,6250' AS List
UNION ALL
SELECT 11 AS Month, '5530,5910' AS List
UNION ALL
SELECT 12 AS Month, '5420,5410,5550,6230,6240,6250' AS List
)
SELECT @RUsToAudit = List
FROM dataTable WHERE Month = @MonthOfYear
如果您打算将其用作另一个选择的IN()
部分,请按以下方式执行:
WITH dataTable AS
(
SELECT 1 AS Month, 5420 as ID
UNION ALL
SELECT 1 AS Month, 5410 as ID
UNION ALL
SELECT 1 AS Month, 5550 as ID
UNION ALL
SELECT 1 AS Month, 6230 as ID
-- etc
)
SELECT *
FROM table
JOIN dataTable on table.ID = dataTable.ID AND dataTable.Month = @MonthOfYear
或
SELECT *
FROM table
WHERE table.ID IN (SELECT ID from dataTable WHERE dataTable.Month = @MonthOfYear)
拥有IN内容的字符串变量将无效。