2016-04-28 58 views
0

如何創建存儲過程以執行與此代碼相同的功能?如何創建存儲過程以更新C#中的多行

string sql = "Update Product set ProductName='" + Product.Name + "' where ProductId=" + Product.Id + ""; 

foreach (var item in Product.pros) 
{ 
    sql += "Update ProductProperties set PropertyValue ='" + item.PropertyValue + "' where PropertyId =" + item.PropertyId + " and ProductId =" + Product.Id + ""; 
} 

db.Database.ExecuteSqlCommand(sql); 
+2

也許去看看關於存儲過程?這看起來很基本,幾乎是本書的第1頁。 – DavidG

+1

「爲我翻譯這段代碼」對Stack Overflow來說不是一個合適的「問題」。 – Blorgbeard

+0

Blorgbeard,在我的代碼中,我通過集合循環來爲集合中的每個項目創建更新語句。我的問題是我怎樣才能做到與存儲過程一樣...我的困惑是如何使存儲過程和循環....謝謝 – Lucy

回答

1

你想要的是一個table valued parameter。我們過去常常做一些非常醜陋的事情,比如將逗號分隔的字符串傳遞給過程並將其拆分,以便我們不必進行多個過程調用,或者傳遞XML。這在2008年推出,而且更容易。

在你的數據庫,你會聲明類型:

CREATE TYPE ProductUpdateTableType AS TABLE 
    (productId int, propertyId int, propertyValue varchar(20)); 

(只是猜測/組成的數據類型。)

然後在你的存儲過程,你會使用這樣的參數:

CREATE PROCEDURE UpdateProducts 
    @productUpdates ProductUpdateTableType READONLY 
AS 
UPDATE products set propertyValue = updates.propertyValue 
FROM 
    ProductProperties product 
    JOIN @productUpdates updates 
     on product.productId = updates.productId 
     and product.propertyId = updates.propertyId 

您使用的參數就像是表格一樣。

在C#端,您需要創建一個DataTable並添加與其表類型匹配的列。然後你會添加包含單個值的行。我通常創建一個類是這樣的:

public class ProductUpdateParameter : DataTable 
{ 
    public ProductUpdateParameter() 
    { 
     Columns.Add("productId", typeof (int)); 
     Columns.Add("propertyId", typeof (int)); 
     Columns.Add("propertyValue", typeof (string)); 
     Columns[2].MaxLength = 20; 
    } 

    public void AddProductUpdate(int productId, int propertyId, string propertyValue) 
    { 
     Rows.Add(productId, propertyId, propertyValue); 
    } 
} 

您創建的ProductUpdateParameter一個實例的方式,並根據需要添加儘可能多的項目。 然後,呼喚你的過程時,你會做這樣的:

var updateParameter = new SqlParameter("@productUpdates", SqlDbType.Structured); 
    updateParameter.TypeName = "dbo.ProductUpdateTableType"; 
    updateParameter.Value = [your data table] 

該參數然後添加到您的SqlCommand並執行它。