0

我有一个数据类型问题。以下代码行适用于我们的数据库:

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'
4

2 回答 2

1

我鼓励您在数据库中创建一个永久表来存储这些信息。具体来说,一个包含 MonthNumber 和 ListItem(都是整数)的表,然后使用 Hogan 建议的查询。

在我看来,您(当前)将业务规则硬编码到数据库中。通过将这些值分离到另一个表中,您可以通过更改表中的数据轻松更改功能,而不是潜入代码进行更改。

这可能需要更多时间来设置,但从长远来看(随着业务流程的变化)它将是一个更优雅的解决方案。

于 2013-10-24T16:34:49.880 回答
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 内容的字符串变量将不起作用。

于 2013-10-24T15:28:15.957 回答