2013-02-01 35 views
0

代碼傳遞一個用戶定義的表類型的SP不宣

create TYPE [dbo].[IntListType] as Table 
(
[Number] [int] null 
) 

create procedure TestProc 
(
    @l IntListType readonly 
) 
as 
begin 
    select * from products where ProductId in (select Number from @l) 
end 

create Table Products 
(
    ProductId 
    ProductName 
) 

insert into Products Values(1, 'One'), 
          (2, 'One'), 
          (3, 'Two'), 
          (4, 'Two'), 
          (5, 'Three'), 
          (6, 'Three') 

問題

注意:這只是一個例子,它似乎很容易只是把查詢的存儲程序,但這只是給我想要做什麼的想法。實時並不像在這個例子中那麼容易。

目前,我想,按ProductID收集幾款產品我必須做這樣的:

declare @l IntListType 
insert into @l values(1),(2) 
exec TestProc @l 

或 聲明@l IntListType 插入到從產品@l 選擇其中產品編號名稱=「一」 exec TestProc @

我想知道是否有可能跳過聲明部分並將選擇結果創建爲IntListType。 我已經嘗試使用要做到這一點「與」

exec TestProc (;with A as(select ProductId from Products where Name = 'One') select * from a) 

但我不能做這樣的工作。

這是甚至可能我正在嘗試做什麼,如果我使用用戶定義的表類型,我總是需要聲明和填充它之前它會工作?

回答

1

對不起,令人失望,但儘可能好,當前SQL Server甚至不允許簡單的計算作爲參數傳遞給過程。因此它不允許查詢被傳遞。

請注意,IN不應與子查詢一起使用,因爲這有時會導致性能問題。改爲使用EXISTS或直接使用JOIN

+0

我在兩張桌子之間的一個小項目上測試過。使用「in」比使用內部連接快10%左右。這個數字很小,所以我不能從中得出任何結論,但是我覺得,如果使用得當,它們會比連接更有優勢。 –

+0

有關IN性能的詳細信息,請參閱此OP的問題http://stackoverflow.com/questions/1200295/sql-join-vs-in-performance。 – AshesToAshes

相關問題