2017-03-01 86 views
2

在SQL Server中,有沒有辦法基於表中列的值調用特定的存儲過程/行內選擇語句?根據SQL Server中行的值調用特定的存儲過程/ select語句

E.g.對於表#IdNumbers(下面)中的每一行,檢查Number列的值 - 如果值爲1,則調用第一個存儲過程,如果值爲2,則調用第二個過程,依此類推。

我想實現類似於下面的代碼(但沒有僞代碼)的東西。

CREATE PROCEDURE [CallSpecificStoredProcedure] 
(
@Name VARCHAR(50) 
,@StartDate DATETIME 
,@EndDate DATETIME 
) 
AS 
BEGIN 
CREATE TABLE #IdNumbers 
( 
    Id UNIQUEIDENTIFIER, 
    Number INT 
) 

INSERT INTO #IdNumbers 
exec GetIdNumbers @StartDate, @EndDate 

--for each row in #IdNumbers 
    --If Number = 1 
    exec StoredProcedure1(Id, Number, @Name, @StartDate, @EndDate) 

    --else If Number = 2 
    exec StoredProcedure2(Id, Number, @Name, @StartDate, @EndDate) 

    --else If Number = 3 
    exec StoredProcedure3(Id, Number, @Name, @StartDate, @EndDate) 
END 

回答

2

您需要使用光標。這希望工程:

CREATE PROCEDURE [p_CallSpecificStoredProcedure] 
(
    @Name VARCHAR(50), 
    @StartDate DATETIME, 
    @EndDate DATETIME 
) 
AS 
BEGIN 
CREATE TABLE #IdNumbers 
( 
    Id UNIQUEIDENTIFIER, 
    Number INT 
) 

INSERT INTO #IdNumbers 
exec GetIdNumbers @StartDate, @EndDate 

DECLARE @Id UNIQUEIDENTIFIER 
DECLARE @Number INT 
DECLARE IdCursor CURSOR FAST_FORWARD FOR 
SELECT Id, Number FROM #IdNumbers 

OPEN IdCursor 
FETCH NEXT FROM IdCursor 
INTO @Id, @Number 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    IF @Number = 1 
    EXEC StoredProcedure1 @Id, @Number, @Name, @StartDate, @EndDate 
    ELSE IF @Number = 2 
    EXEC StoredProcedure2 @Id, @Number, @Name, @StartDate, @EndDate 
    ELSE IF @Number = 3 
    EXEC StoredProcedure3 @Id, @Number, @Name, @StartDate, @EndDate 

    FETCH NEXT FROM IdCursor 
    INTO @Id, @Number 
END 
CLOSE IdCursor 
DEALLOCATE IdCursor 

END 
+0

太好了。你有點快。 –

+0

@teovankot我讀了你的。這個想法很好,但有一些錯誤,大部分是從 –

+0

這個問題繼承而來的,我有一種感覺,我需要使用遊標來獲得解決方案 - 這看起來像我之後的事情。你知道有什麼其他的方法來實現這個嗎?我在遊標周圍看到了許多恥辱,但我個人不知道是否/爲什麼使用它們是好事還是壞事 - 我認爲這與效率有關。 – axel

1

我想通過您搜索CURSOR

CREATE PROCEDURE [CallSpecificStoredProcedure] 

@Name VARCHAR(50) 
,@StartDate DATETIME 
,@EndDate DATETIME 

AS 
BEGIN 
CREATE TABLE #IdNumbers 
( 
    Id UNIQUEIDENTIFIER, 
    Number INT 
) 

INSERT INTO #IdNumbers EXEC GetIdNumbers @StartDate, @EndDate --Hope here you insert your numbers 

DECLARE @Id UNIQUEIDENTIFIER 
DECLARE @Number INT 

DECLARE NUMBERS_CURSOR CURSOR 
    LOCAL STATIC READ_ONLY FORWARD_ONLY 
FOR 
SELECT Id, Number 
FROM #IdNumbers 

OPEN NUMBERS_CURSOR 
FETCH NEXT FROM NUMBERS_CURSOR INTO @Id, @Number 
WHILE @@FETCH_STATUS = 0 --If there is still rows 
BEGIN 
    --here your logic 
    IF @Number = 1 
    BEGIN 
    EXEC StoredProcedure1 @Id, @Number, @Name, @StartDate, @EndDate 
    END 
    IF @Number = 2 
    BEGIN 
    EXEC StoredProcedure2 @Id, @Number, @Name, @StartDate, @EndDate 
    END 

    FETCH NEXT FROM NUMBERS_CURSOR INTO @Id, @Number 
END 
CLOSE NUMBERS_CURSOR 
DEALLOCATE NUMBERS_CURSOR 
相關問題