2

這是我開始寫的存儲過程 問題是我無法弄清楚如何處理從電視機中讀取值的部分:使用動態SQL - 自定義通用多動作存儲過程(與TVPar)

必須聲明表變量「@TestMultiActionViaRowIndexTVPar」。

ALTER Proc [dbo].[MultiActionViaRowIndexSpTVP] 
    @SelectedSDTOName varchar (50), @SelectedAction varchar(10), @TestMultiActionViaRowIndexTVPar dbo.TestMultiActionViaRowIndexTVType READONLY 
    as BEGIN 

    declare @CmdStr varchar(500) = ''; 
     if(@SelectedAction = 'SELECT') Begin --test for one of the "Action" types 
      SET @CmdStr = 'SELECT * FROM ' + @SelectedSDTOName + 
      ' WHERE RowIndex in (SELECT RowIndex FROM @TestMultiActionViaRowIndexTVPar)' 
     End 

     --else - other Action - @CmdStr will be according to action... 

    --finally execute constructed Cmdstr 
    Exec(@CmdStr); 
    END 

回答

2

使用sp_executesql的傳遞一個TVP或任何其他參數參數化動態SQL:

ALTER PROC [dbo].[MultiActionViaRowIndexSpTVP] 
     @SelectedSDTOName varchar (50) 
    , @SelectedAction varchar(10) 
    , @TestMultiActionViaRowIndexTVPar dbo.TestMultiActionViaRowIndexTVType READONLY 
AS 
DECLARE @CmdStr nvarchar(MAX); 

IF @SelectedAction = 'SELECT' 
BEGIN 
    SET @CmdStr = 'SELECT * FROM ' + @SelectedSDTOName + 
      ' WHERE RowIndex in (SELECT RowIndex FROM @TestMultiActionViaRowIndexTVPar);' 
END; 

EXEC sp_executesql 
    @CmdStr 
    ,N'@TestMultiActionViaRowIndexTVPar dbo.TestMultiActionViaRowIndexTVType READONLY' 
    ,@TestMultiActionViaRowIndexTVPar = @TestMultiActionViaRowIndexTVPar; 
GO 
+0

一個相當複雜的表情,我能理解中線存在邏輯上,但最後 - '@ par = @ par'?哦..它不接近C/C++/C#編程習慣用法 –