我有一个登录表单,如:
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,它将值输入DGRegion
和DGState
表?
点击提交后我正在使用asp.net。
问题是:我可以直接在DGRegion
表中输入值,但如何在表DGState
中输入状态引用?
答案 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: