SQL游标,而不是select语句的并集

时间:2018-06-19 19:53:58

标签: sql stored-procedures cursor union-all sql-server-2017

我有一个需要更新的SQL Server过程。当前,它具有3个INPUT参数(程序ID),并使用这些参数运行由UNION ALL连接的3个SELECT语句。现在,要求已更改为可以传入2或3个INPUT参数的地方。

创建另一个过程,并根据IF条件从我的ASP.Net站点中调用任何一个过程,对我来说都是一个糟糕的主意。相反,我希望能够压缩存储过程以允许使用可变数量的INPUT参数并运行相同的select语句,而不必使用UNION ALL。

当前是这样的:

SELECT name, startdate, enddate FROM xyztable WHERE x1 = id1
UNION ALL
SELECT name, startdate, enddate FROM xyztable WHERE x1 = id2
UNION ALL
SELECT name, startdate, enddate FROM xyztable WHERE x1 = id3

将光标改为执行此操作的理想方法吗? (对它们的工作方式感到困惑)

更新

我尝试了以下操作以及使用IN (xxx, xxx, xxx)的情况,但是,它使每条记录增加了三倍。我需要对代码做大的修改吗?

SELECT 
    WS.ProgramID,
    WS.ItemID,
    WS.Day,
    CASE DATEPART(WEEKDAY, DATEADD(DAY, WS.Day - 1, WE.eventstartdate))
       WHEN 1 THEN 'Sun'
       WHEN 2 THEN 'Mon'
       WHEN 3 THEN 'Tue'
       WHEN 4 THEN 'Wed'
       WHEN 5 THEN 'Thu'
       WHEN 6 THEN 'Fri'
       WHEN 7 THEN 'Sat'
       ELSE 'N/A'
    END + ' '
        + CONVERT(CHAR(12), DATEADD(DAY, WS.Day - 1, WE.eventstartdate), 101) AS Date, CONVERT(VARCHAR(15), CONVERT(TIME, SUBSTRING(WS.TimeSlot, 0, 6)), 100) AS 'Begin TIME',
    CONVERT(VARCHAR(15), CONVERT(TIME, SUBSTRING(WS.TimeSlot, 7, 6)), 100) AS 'End TIME',
    WS.TimeSlot,
    WS.SlotType,
    WSSTC.Description AS SlotTypeDescription,
    WS.SlotInfo,
    WSSIC.Description AS SlotInfoDescription,
    ISNULL(WSI.TalkID, 0) AS TalkID,
    LEFT(WPI.FirstName, 10) + ' ' + LEFT(WPI.LastName, 10) + ' ('
           + LEFT(WEA.institution, 10) + ')' + ' - '
           + LEFT(WSI.Title, 10) + '...' + RIGHT(WSI.Title, 10) AS Talk,
    WPI.FirstName,
    WPI.LastName,
    WEA.institution,
    WSI.AuthorLine,
    WSI.Title,
    LEFT(WSI.Abstract, 1) AS Abstract,
    WS.Location,
    WS.Addendum,
    WE.EventName
FROM   
    dbo.WebSpeakerInfo WSI
INNER JOIN 
    dbo.WebPersonalInfo WPI ON WSI.UserID = WPI.UserID
INNER JOIN 
    dbo.webeventaffiliation WEA ON WPI.UserID = WEA.userid
                                AND (WEA.eventid = 3515 OR wea.eventid = 3516 OR WEA.eventid = 3471)
RIGHT OUTER JOIN 
    dbo.WebScheduleSlotTypeCodes WSSTC
RIGHT OUTER JOIN 
    dbo.WebSchedules WS ON WSSTC.SlotType = WS.SlotType 
    ON WSI.TalkID = WS.TalkID
LEFT OUTER JOIN 
    dbo.WebScheduleSlotInfoCodes WSSIC ON WS.SlotInfo = WSSIC.SlotInfo
INNER JOIN 
    dbo.WebEvents WE ON (WE.eventid = 3515 OR we.eventid = 3516 OR WE.eventid = 3471)
WHERE  
    (WS.ProgramID = 3515 OR ws.ProgramID = 3516 OR ws.ProgramID = 3471)
    AND WS.SlotType <> 6

1 个答案:

答案 0 :(得分:1)

您可以使用一系列相等条件,它们之间有or个条件(或in条件,这只是它们的简写)。由于null永远不能等于一个值,而您传递的第二个和第三个ID的null只会被忽略:

SELECT name, startdate, enddate FROM xyztable WHERE x1 IN (id1, id2, id3)