【发布时间】:2017-02-26 20:21:00
【问题描述】:
我有两张桌子
tbl_orgs:
和tbl_location_records:
我正在使用存储过程将数据插入这些表中。
插入组织
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsOrg]
(@orgName nvarchar(50),
@orgCity nvarchar(50),
@orgArea nvarchar(50),
@orgTel nvarchar(50),
@orgEmail nvarchar(50),
@orgType nvarchar(50),
@orgStatus nvarchar(50),
@strOwner nvarchar(50),
@db_tstamp datetime2)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_orgs] ([orgName], [orgCity], [orgArea], [orgTel], [orgEmail], [orgType], [orgStatus], [strOwner], [db_tstamp])
VALUES (@orgName, @orgCity, @orgArea, @orgTel, @orgEmail, @orgType, @orgStatus, @strOwner, @db_tstamp);
SELECT
orgID, orgName, orgCity, orgArea, orgTel, orgEmail, orgType,
orgStatus, strOwner, db_tstamp
FROM
tbl_orgs
WHERE
(orgID = SCOPE_IDENTITY())
插入位置记录
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsLoc]
(@userID int,
@orgID int,
@jobID int,
@strLat numeric(18, 0),
@strLong numeric(18, 0),
@strOwner varchar(50),
@db_tstamp datetime2)
AS
SET NOCOUNT OFF;
INSERT INTO [tbl_location_records] ([userID], [orgID], [jobID], [strLat], [strLong], [strOwner], [db_tstamp])
VALUES (@userID, @orgID, @jobID, @strLat, @strLong, @strOwner, @db_tstamp);
SELECT
recordID, userID, orgID, jobID, strLat, strLong, strOwner, db_tstamp
FROM
tbl_location_records
WHERE
(recordID = SCOPE_IDENTITY())
一旦成功插入组织记录,我想使用单一表单添加插入组织的位置记录。
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["IBS_3"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsOrg", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("orgName", SqlDbType.NVarChar).Value = txtOrgName.Text;
cmd.Parameters.Add("orgCity", SqlDbType.NVarChar).Value = txtCity.Text;
cmd.Parameters.Add("orgArea", SqlDbType.NVarChar).Value = txtArea.Text;
cmd.Parameters.Add("orgTel", SqlDbType.NVarChar).Value = txtTele.Text;
cmd.Parameters.Add("orgEmail", SqlDbType.NVarChar).Value = txtEmail.Text;
cmd.Parameters.Add("orgType", SqlDbType.NVarChar).Value = txtOrgType.Text;
cmd.Parameters.Add("orgStatus", SqlDbType.NVarChar).Value = txtStatus.Text;
cmd.Parameters.Add("@strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("@db_tstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
SqlCommand cmdloc = new SqlCommand("spInsLoc", conn);
cmdloc.CommandType = CommandType.StoredProcedure;
cmdloc.Parameters.Add("orgID", SqlDbType.Int).Value =
}
}
试图从这个链接获得一些理解,但我对此一无所知..
Inserting to one table, insert the ID to second table
任何帮助表示赞赏。
谢谢。
【问题讨论】:
-
旁注:您应该不为您的存储过程使用
sp_前缀。微软有reserved that prefix for its own use (see Naming Stored Procedures),你确实冒着在未来某个时候发生名称冲突的风险。 It's also bad for your stored procedure performance。最好只是简单地避免sp_并使用其他东西作为前缀 - 或者根本不使用前缀! -
@marc_s 当然谢谢。我只使用'sp'。但我肯定会记住这一点。
标签: c# asp.net sql-server stored-procedures insert