使用LIST INSERT到存储过程

时间:2013-07-05 10:58:48

标签: c# sql-server linq-to-sql stored-procedures

我有这个存储过程:

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不支持用户定义的表类型,因此我无法使用表。 :(

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

您应该使用表类型参数。

在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;
    }
相关问题