簡體   English   中英

使用LIST插入存儲過程

[英]INSERT using LIST into Stored Procedure

我有這個存儲過程:

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-to-SQL類中插入退出,因此我想從應用程序中插入列表,這可能嗎?

我已經看到,然后使用SELECT語句完成了操作,但是使用INSERT時卻沒有完成。
更新:由於LINQ to SQL不支持用戶定義的表類型,因此我不能使用表。 :(

如果您使用的是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 

您應該使用表類型參數。

在sql server中創建一個類和Table類型。 名稱和順序應匹配。 現在,使用以下代碼將列表轉換為Table並將其作為參數傳遞給該過程。

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

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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM