如何使用存储过程将FK放入另一个表中

时间:2011-09-08 12:35:21

标签: c# sql stored-procedures

我有一个登录表单,如:

Username: Ashish

Password: Pass

Contact no: 1234567890

State: Maharashtra

有两张桌子:

create table DGRegion
(DG_Regionno Int Identity (1,1) NOT Null constraint pk1 Primary Key,
 DG_Username varchar(50),
 DG_Password varchar(50), 
 DG_Contactno int ,
 DG_StateNo int References DGState(DG_stateno))


Create table DGState 
 (DG_stateno Int Identity (1,1) NOT Null constraint pk Primary Key ,
  DG_State varchar (50))

现在我如何创建一个存储过程P,它将值输入DGRegionDGState表?

点击提交后我正在使用asp.net。

问题是:我可以直接在DGRegion表中输入值,但如何在表DGState中输入状态引用?

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

CREATE PROCEDURE dbo.EnterLoginData(@Username VARCHAR(50), @Password VARCHAR(50),
                                    @ContactNo INT, @StateName VARCHAR(50)) 
AS BEGIN 
   DECLARE @StateID INT

   -- check if state already exists
   IF EXISTS(SELECT * FROM dbo.DGState WHERE DG_State = @StateName)

      -- if it exists - retrieve the DG_StateNo
      SELECT @StateID = DG_StateNo
      FROM dbo.DGState 
      WHERE DG_State = @StateName

   ELSE BEGIN

      -- if it doesn't exists - insert new row 
      INSERT INTO dbo.DG_State(DG_State) VALUES(@StateName);

      -- get the newly inserted row's ID using SCOPE_IDENTITY()
      SELECT @StateID = SCOPE_IDENTITY()
   END

   INSERT INTO 
       dbo.DGRegion(DG_Username, DG_Password, DG_ContactID, DG_StateNo)
   VALUES(@Username, @Password, @ContactNo, @StateID)
END

答案 1 :(得分:1)

在sp:

  • 检查状态是否在状态表中
  • 如果没有,请将其放入状态表
  • 获取状态表的id(DG_stateno),放入变量
  • 执行您的插入