我在Visual Studio 2010中使用C#,.NET framework 3.5編寫了一個Web服務。我的問題可能很基本,但我沒有使它成功運行。在SQL Server 2008中對不同表格進行多次插入
我可以成功地通過Web服務將數據提交給SQL數據庫。我希望能夠做到的是在SQL db中的一個表中插入記錄/行時,我希望能夠將數據插入到另一個表中,比如說表B.表B有5個列。它將從前一個表(通過Web服務插入的表A)中獲取兩個列值。表B中的一列是主鍵值,其餘兩列將具有靜態文本值。
下面是表的結構的
id int (primary key)
CustName varchar(45)
CustAddress varchar(45)
CustContacts varchar(45)
CustQuoteDate varchar(45)
CustLoginId varchar(45)
表B結構:
id int (primary key)
OrderId varchar(45) NOT NULL //This will get value from table A's Primary key
OrderReqDate [varchar](45) NOT NULL //This will get value from table A's CustQuotDate
OrderStatus [varchar](45) NOT NULL // This will be a static value "Requested"
OrderGroup [varchar](45) NOT NULL // This will be a static value "GGGG"
所以我測試了我的第二個插入查詢:
INSERT INTO dbo.TableB(OrderId , currstatus, OrderReqDate, OrderGroup)
SELECT ta.id, 'REQUESTED', ta.CustQuoteDate, 'GGGG' from dbo.TableA ta
where ta.CustLoginId = 'kenw1'
因此每個新加入TableA中的CustLoginId,第二個表即。 TableB還從tableA中獲得一些行插入。
我的問題是如何/在哪裏編輯我的Web服務代碼下面能夠做第二次插入?您將非常感謝您幫助我的時間和精力。 TIA。
這裏是我的web服務:
[WebMethod(Description = "Adds a Customer Request Form data to the database [TableA].")]
public void AddCustRequestRecord(string CustName, string CustAddress, string custContacts, string custQuoteDate, string CustLoginId)
{
//Static text values for columns in tableB
string OrderStatus = "REQUESTED";
string OrderGroup = "GGGG";
string connectionString =
ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
DateTime now = DateTime.Now;
string QuoteDt = now.ToString();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO TableA "
+ "(CustName, CustAddress, custContacts, CustLoginId, custQuoteDate) "
+ "VALUES (@CustName, @CustAddress, @custContacts, @CustLoginId,'" + Quotedt + "')";
cmd.Parameters.AddWithValue("CustName", CustName);
cmd.Parameters.AddWithValue("CustAddress", CustAddress);
cmd.Parameters.AddWithValue("custContacts", custContacts);
cmd.Parameters.AddWithValue("CustLoginId", CustLoginId);
cmd.Parameters.AddWithValue("custQuoteDate", custQuoteDate);
cmd.Connection = conn;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
// Handle the error using your own preferred error-handling method
}
finally
{
conn.Close();
}
}
}
答案很簡單,但是你有什麼試過? – 2012-08-02 11:36:06
你不能在插入tableA插入到B時使用觸發器嗎? – Chris 2012-08-02 11:38:10
@Chris Moutray,我只是嘗試創建第二個命令對象,第二個連接有第二個插入。沒有錯誤,但沒有插入我的第二張桌子。 – Nemo 2012-08-02 11:52:31