2011-04-07 127 views
0

任何可以告訴我如何將ID的LIst發送到SQL中的存儲過程。存儲過程..使用SQL服務器

我需要從我的控制器發送列表,以便可以使用存儲過程一次執行該ID列表。

感謝

+0

我想你可能需要更多的信息在這裏。你打算用這些ID做什麼?他們是否要進入where子句? – 2011-04-07 16:19:40

+0

是nathan,它將去where子句中更新表格中的特定Ids。使用這個sP。 – user300485 2011-04-07 16:21:08

回答

6

在SQL Server 2008和最多可以使用Table-Valued Parameters

+0

也很有幫助,這裏是一個鏈接,顯示如何從.net http://dotnetspeaks.com/DisplayArticle.aspx?ID=47 – 2011-04-07 16:22:11

+0

@nathan gonzalez對不起,我認爲鏈接有一個例子 - 我最近自己也在做一些TVP。這個鏈接有一個更好的完整的概述:http://msdn.microsoft.com/en-us/library/bb675163.aspx – 2011-04-07 16:28:17

+0

msdn鏈接確實有一個很好的範例,但最後一個關於流選項是有點簡潔。我在這裏寫了一篇特別詳細介紹流式傳輸選項的文章:http://www.sqlservercentral.com/articles/SQL+Server+2008/66554/(需要註冊)。 – 2011-04-07 16:53:41

1

怎麼樣的Id的逗號分隔的字符串?

問題是SQL Server不支持數組數據類型(或類似)

+0

是的,我們可以發送id的字符串,但是如何用sp中分隔的逗號分隔這些id的字符串。 – user300485 2011-04-07 16:21:42

+0

看起來像Rene147增加了一個有用的鏈接 – 2011-04-07 16:25:04

3

最好的辦法(2008年),是通過它作爲表格。 2008年以前,你必須使用CSV格式的VarChar然後將其分開。

對此有讀:http://www.sommarskog.se/arrays-in-sql-2008.html

+0

對於2005年(甚至是2000年),XML通常是比CSV更好的方法。更清潔,更快速,並可輕鬆擴展到多列。從您鏈接到的文章中:「實際上,XML是最快的方法,不需要在服務器上做任何準備工作:您不必激活CLR並創建函數,也不需要爲一個表值參數「。 – Lucero 2011-04-07 16:29:08

+0

偉大的鏈接... :-) – IrishChieftain 2011-04-07 16:48:29

1

聽起來像是你需要沿着此線的東西:

CREATE FUNCTION [dbo].[Split_String] 
(
    @ConcatValues VARCHAR(MAX) 
) 
RETURNS @Values Table 
(
    Value VARCHAR(MAX) 
) 
AS 
/************************************************************************************************************** 
Purpose: When called from a stored procedure and passed a character delimited parameter (of String data type values), 
      this function returns a table named "@Values" with a field named "Value" (populated with the parameter list) 
      which can then be referenced in the stored procedure. 
      This function requires that the delimited paramater have as its first character the delimiter character. 

Sample calls: 
      Select * from [dbo].[Split_String](';dog;cat;mouse') 
      Select * from [dbo].[Split_String]('| dog| cat| mouse|')   
      Select * from [dbo].[Split_String]('|')  
      Select * from [dbo].[Split_String]('')  

**************************************************************************************************************/ 

BEGIN 
    --Indexes to keep the position of searching 
    DECLARE @Delim CHAR(1) 
    Declare @Pos1 Int 
    Declare @Pos2 Int 

    --Identify delimiter character 
    SET @Delim = SUBSTRING(@ConcatValues, 1, 1) 
    --Append delimiter character 
    Set @ConcatValues = @ConcatValues + ' ' + @Delim  
    --Set 1st character of 1st value 
    Set @Pos2 = 2 

    While @Pos2 < Len(@ConcatValues) 
    BEGIN 
     Set @Pos1 = CharIndex(@Delim, @ConcatValues, @Pos2) 
     Insert @Values SELECT LTRIM(RTRIM(Substring(@ConcatValues, @Pos2, @Pos1 - @Pos2))) 
     --Go to next non-delimiter character 
     Set @Pos2 = @Pos1 + 1 
    END 
    RETURN 
END 


GO 

我們分割功能是通用於各種場合的使用和依賴於分隔符由字符串中的第一個字符標識。如果你只在一個地方需要它,它可能會被簡化一點。