在连续的SQL查询中提供自动生成的ID作为另一个表的列值

时间:2015-03-22 14:03:14

标签: c# sql sql-server

我有两张表,分别是:tblEventServicetblEventItem ..

以下是两者的列:

columns

这是我用来插入两张表的方法,正如@ M.Ali在答案中所建议的那样:

public int concurrentInsert(EventService eventServiceObj, EventItem eventItem)
        {
            string query = @" Declare @EventServiceID INT;

                            insert into tblEventService(ServiceDate,ServiceVenue,Status,CustomerRemarks,ServiceID,VendorID,EventID) 
                            values(@ServiceDate,@ServiceVenue,@Status,@CustomerRemarks,@ServiceID,@VendorID,@EventID);

                             SELECT @EventServiceID = SCOPE_IDENTITY();


                            INSERT INTO TableEventItem(EventServiceID,VendorItemID,Price,Quantity,CustomerRemarks)
                            VALUES (@EventServiceID , @VendorItemID , @Price,@Quantity,@CustomerRemarks)";

            List<SqlParameter> lstParams = new List<SqlParameter>();

            lstParams.Add(new SqlParameter("@ServiceDate", eventServiceObj.ServiceDate));
            lstParams.Add(new SqlParameter("@ServiceVenue", eventServiceObj.ServiceVenue));
            lstParams.Add(new SqlParameter("@Status", eventServiceObj.Status));
            lstParams.Add(new SqlParameter("@CustomerRemarks", eventServiceObj.CustomerRemarks));
            lstParams.Add(new SqlParameter("@ServiceID", eventServiceObj.ServiceID));
            lstParams.Add(new SqlParameter("@VendorID", eventServiceObj.VendorID));
            lstParams.Add(new SqlParameter("@EventID", eventServiceObj.EventID));

            lstParams.Add(new SqlParameter("@EventServiceID", eventItem.EventServiceID));
            lstParams.Add(new SqlParameter("@VendorItemID", eventItem.VendorItemID));
            lstParams.Add(new SqlParameter("@Price", eventItem.Price));
            lstParams.Add(new SqlParameter("@Quantity", eventItem.Quantity));
            lstParams.Add(new SqlParameter("@CustomerRemarks", eventItem.CustomerRemarks));

当我通过硬编码值检查它时查询工作正常。现在我有一个问题:

应该在insert方法中提供自动生成的ID @EventServiceID ..如何在C#代码中提供?

这是我正在使用的C#代码中的方法:

for (int i = 0; i < rptr.Items.Count; i++)
            {
                EventService eventService = new EventService();
                EventServiceLogic eventServiceLogic = new EventServiceLogic();

                eventService.ServiceID = Convert.ToInt32(((HiddenField)rptr.Items[i].FindControl("hdnServiceID")).Value);
                eventService.VendorID = Convert.ToInt32(((HiddenField)rptr.Items[i].FindControl("HiddenField1")).Value);

                TextBox txtDate = (TextBox)rptr.Items[i].FindControl("txtServiceDate");
                DateTime eventDate = new DateTime();

                if (DateTime.TryParseExact(txtDate.Text, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out eventDate))
                {
                    eventService.ServiceDate = eventDate;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(lnkBtnOrder, lnkBtnOrder.GetType(), "key", "alert('Invalid Date!Please enter in the format : Date-Month-Year')", true);
                    return;
                }

                eventService.ServiceVenue = txtVenueName.Text;
                eventService.CustomerRemarks = txtRemarks.Text;
                eventService.Status = "pending";
                eventService.EventID = Convert.ToInt32(ddlMyEvents.SelectedValue);

                EventItem eventItem = new EventItem();

                eventItem.VendorItemID = Convert.ToInt32(((HiddenField)rptr.Items[i].FindControl("hdnVendorItemID")).Value);
                eventItem.CustomerRemarks = eventService.CustomerRemarks = txtRemarks.Text;
                eventItem.Quantity = Convert.ToInt32(((TextBox)rptr.Items[i].FindControl("txtQty")).Text);

    eventItem.EventServiceID = //this is auto-generated. how should i provide this value ?


                int registerServiceResult = eventServiceLogic.concurrentInsert(eventService,eventItem);

                if (registerServiceResult > 0)
                {
                    lblTotal.Text = "This Works!";  
                }
                else
                {
                    lblTotal.Text = "This Doesn't Work!";
                }
            }

2 个答案:

答案 0 :(得分:4)

Google系统函数SCOPE_IDENTITY(),您可以像这样编写两个插件......

单行插入

Declare @EventServiceID INT;

insert into tblEventService(ServiceDate,ServiceVenue,Status,CustomerRemarks,ServiceID,VendorID,EventID) 
values(@ServiceDate,@ServiceVenue,@Status,@CustomerRemarks,@ServiceID,@VendorID,@EventID);

 SELECT @EventServiceID = SCOPE_IDENTITY();


INSERT INTO TableEventItem(EventServiceID , Col2 , Col3 , ....)
VALUES (@EventServiceID , @var2 , @var3 , ....)

多行插入

如果您正在进行多次插入,则可以执行类似....

的操作
Declare @EventSrvcID_Table TABLE
(EventServiceID INT,
 Col1 [Datatype],
 Col2 [Datatype]) ;

insert into tblEventService(ServiceDate,ServiceVenue,Status,CustomerRemarks,ServiceID,VendorID,EventID) 
OUTPUT inserted.EventServiceID , inserted.Col1 , inserted.Col2 
        INTO @EventSrvcID_Table(EventServiceID , Col2 , Col3)
values(@ServiceDate1,@ServiceVenue1,@Status1,@CustomerRemarks1,@ServiceID1,@VendorID1,@EventID1)
     ,(@ServiceDate2,@ServiceVenue2,@Status2,@CustomerRemarks2,@ServiceID2,@VendorID2,@EventID2);


INSERT INTO TableEventItem(EventServiceID , Col2 , Col3 , ....)
SELECT EventServiceID , Col2 , Col3
FROM @EventSrvcID_Table

答案 1 :(得分:0)

我需要的内容:自动生成的ID,在插入一个表时创建,该ID将作为其他表中的列值使用。

表名: 1)tblEventService(自动生成的id:EventServiceID)2)tblEventItem

我做了什么: tblEventService的方法:

public int Insert(EventService eventServiceObj)
        {
            string query = "insert into tblEventService(ServiceDate,ServiceVenue,Status,CustomerRemarks,ServiceID,VendorID,EventID) values(@ServiceDate,@ServiceVenue,@Status,@CustomerRemarks,@ServiceID,@VendorID,@EventID)";
            List<SqlParameter> lstParams = new List<SqlParameter>();

            lstParams.Add(new SqlParameter("@ServiceDate", eventServiceObj.ServiceDate));
            lstParams.Add(new SqlParameter("@ServiceVenue", eventServiceObj.ServiceVenue));
        ..... 
//similarly add other parameters too 

            DBUtility.ModifyData(query, lstParams); //this query is an Insert Query

            string query1 = "select EventServiceID from tblEventService where ServiceDate=@ServiceDate and ServiceVenue=@ServiceVenue and Status=@Status and CustomerRemarks=@CustomerRemarks and ServiceID=@ServiceID and VendorID=@VendorID and EventID = @EventID";  //this query selects the EventServiceID of the data inserted by the corressponding User . This will make sure to select correct data even if there are concurrent entries.

            List<SqlParameter> lstParams1 = new List<SqlParameter>();

            lstParams1.Add(new SqlParameter("@ServiceDate", eventServiceObj.ServiceDate));
            lstParams1.Add(new SqlParameter("@ServiceVenue", eventServiceObj.ServiceVenue));
           //similarly add other parameters too 

            DataTable dt = DBUtility.SelectData(query1, lstParams1);
            return Convert.ToInt32(dt.Rows[0]["EventServiceID"]);
        } //this will return the autogenerated id which i require in the other table!

因此,做的是插入,然后选择!这对我有用..!其中一个答案也可以用作query但是我在另一个表中给出该参数有问题!