2013-07-05 49 views
1

我有這個存儲過程:INSERT使用LIST到存儲過程

CREATE PROCEDURE [RSLinxMonitoring].[InsertFeatures] 
    @Features nvarchar(50), 
    @TotalLicenses int, 
    @LicensesUsed int, 
    @ServerName nvarchar(50) 
AS 
    SET NOCOUNT ON 

    INSERT INTO [RSLinxMonitoring].[FeatureServer] 
     ([Features] 
      ,[TotalLicenses] 
      ,[LicensesUsed] 
     ,[Server]) 
    VALUES(@Features 
      ,@TotalLicenses 
      ,@LicensesUsed 
      ,@ServerName) 

它能正常工作,但因爲我需要插入退出從我的C#的LINQ到SQL類了一下,我想從我的應用程序中插入一個列表來代替,這可能嗎?

我已經看到它已經完成,然後使用SELECT聲明,但沒有使用INSERT時。
更新: 由於LINQ to SQL不支持用戶定義的表類型我不能表。 :(

+1

你有沒有在存儲過程中聽到表類型參數的?如果你不想使用ORM考慮傳遞表類型參數 – Ehsan

+0

#Ehsan Ullah看起來interresting。但是我是否需要遍歷列表,以及應用程序發送什麼類型? – mortenstarck

+0

看到我的回答如下 – Ehsan

回答

3

如果您AR e上面使用SQL server 2008 &,可以使用下面的解決方案。 申報表型,如:

CREATE TYPE FeatureServerType AS TABLE 
(
    [Features] nvarchar(50) 
    ,[TotalLicenses] int 
    ,[LicensesUsed] int 
    ,[Server] nvarchar(50) 
); 

這樣使用它:

CREATE PROCEDURE [RSLinxMonitoring].[InsertFeatures] 
    @TabletypeFeatures FeatureServerType READONLY 
AS 
    SET NOCOUNT ON; 

    INSERT INTO [RSLinxMonitoring].[FeatureServer] 
     ([Features] 
      ,[TotalLicenses] 
      ,[LicensesUsed] 
     ,[Server]) 
    SELECT * FROM @TabletypeFeatures 
+0

我試過你的例子。但Linq-to-SQL不支持用戶定義的表類型。它給了我這個錯誤「必須爲UDT參數設置UdtTypeName屬性」 – mortenstarck

+0

是的,Linq-to-SQL當前不支持用戶定義的表類型。使用可以使用代碼中的簡單SP調用。 –

2

應使用表類型參數。

在SQLServer,創建一個類和表型。名稱和順序應匹配。現在只需使用下面的代碼轉換您的清單表,並把它作爲一個paremeter的程序。

存儲過程的幫助,在這裏可以看到

http://blog.sqlauthority.com/2008/08/31/sql-server-table-valued-parameters-in-sql-server-2008/

public static DataTable ToDataTable<T>(this List<T> iList) 
    { 
     DataTable dataTable = new DataTable(); 
     PropertyDescriptorCollection propertyDescriptorCollection = 
      TypeDescriptor.GetProperties(typeof(T)); 
     for (int i = 0; i < propertyDescriptorCollection.Count; i++) 
     { 
      PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i]; 
      Type type = propertyDescriptor.PropertyType; 

      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) 
       type = Nullable.GetUnderlyingType(type); 


      dataTable.Columns.Add(propertyDescriptor.Name, type); 
     } 
     object[] values = new object[propertyDescriptorCollection.Count]; 
     foreach (T iListItem in iList) 
     { 
      for (int i = 0; i < values.Length; i++) 
      { 
       values[i] = propertyDescriptorCollection[i].GetValue(iListItem); 
      } 
      dataTable.Rows.Add(values); 
     } 
     return dataTable; 
    } 
+2

是的,這個。但請注意,表格類型不能改變。您需要在每次更改時重新創建它們,這也意味着您需要重新編譯每個使用該類型的存儲過程。 –

+0

重新編譯意味着在重新創建表類型之前,必須刪除所有正在使用此類型的存儲過程,然後更改表類型。改變後,你將不得不再次創建sp。 :) – Ehsan

+1

我傾向於首先重命名舊的表格類型(這是可行的,而不是刪除它)。然後我用舊名稱創建新類型,然後編輯SP並按F5。之後,我刪除在第一步中重命名的表格類型。 –