有同事詢問他要如何取得 Exec(t-sql) 裡面的值,因為 Exec 與外面是不同的 Scope 所以要取得裡面值有以下幾種情況。
- Store Procedue ,透過 sp_executesql + 它的 output 參數來取得資料,例如, - 1 
 2
 3
 4
 5
 6
 7- DECLARE @sql NVARCHAR(max), @outputcode NVARCHAR(4000); 
 SET @sql =
 '
 EXEC SP_GETSERNO @RETURNS=@outputcode output
 ';
 exec sp_executesql @sql, N'@outputcode NVARCHAR(4000) out', @outputcode out
 SELECT @outputcode;
- 取得 t-sql 裡面的內容,需要先建立 temp table ,或是 TABLE 變數,然後在 Exec 的 t-sql 裡面使用,例如, - 1 
 2
 3
 4- DECLARE @ATT_IDENT TABLE (ATT_IDENT int); 
 INSERT @ATT_IDENT
 exec ('SELECT top 1 ATT_IDENT FROM [dbo].[myTable]');
 select * FROM @ATT_IDENT;
- t-sql,透過 sp_executesql + 它的 output 參數來取得資料,例如, - 1 
 2
 3- DECLARE @IDT NUMERIC 
 exec sp_executesql N'SELECT TOP 1 @IDT = ATT_IDENT FROM [dbo].[myTable]', N'@IDT NUMERIC out', @IDT OUT
 SELECT @IDT;
- 透過 OPENQUERY 的方式,詳細可以參考「讓 Execute 可以搭配 Select Into,而不再只有 Insert into」