0

我有3张桌子-

1. Country (CountryName, CID (PK- AutoIncrement))
2. State (SID(PK- AutoIncrement), StateName, CID (FK to Country)
3. City (CityName, CID, SID (FK to State)

现在我只需要将名称插入到 CountryName、StateName 和 CityName 的三个表中。ID 需要更新。

Create PROCEDURE sp_place(
    @CountryName char(50),
    @StateName  varchar(50),
    @CityName   nchar(20)
    )
AS
DECLARE @CountryID int, @StateID int, @CityID int;

Set NOCOUNT OFF

BEGIN TRANSACTION

INSERT INTO dbo.Country VALUES (@CountryName);
SET @CountryID = SCOPE_IDENTITY();

IF @@ERROR <> 0 
BEGIN     
ROLLBACK     
RETURN 
END 

Insert into dbo.State VALUES (@StateName, @CountryID);
SET @StateID = SCOPE_IDENTITY();
IF @@ERROR <> 0 
BEGIN     
ROLLBACK     
RETURN 
END 

Insert into dbo.City VALUES (@CityName, @StateID);
SET @CityID= SCOPE_IDENTITY();

Commit

当我两次输入国家/地区时,该值不应更改。例如:如果我进入印度 CountryID=1 的值,当我再次进入印度时,CountryID 的值不应该增加。

我是怎么做到的?我的 SP 每次插入都会改变。

4

4 回答 4

2

您可以检查该国家/地区是否已存在并检索 countryID

IF NOT EXISTS(Select 1 FROM Country Where CountryName=@Country)
BEGIN
    INSERT INTO dbo.Country VALUES (@CountryName);
    SET @CountryID = SCOPE_IDENTITY();
END
ELSE
    Select @CountryID = CountryID From Country Where CountryName=@Country

如果需要State,您可以执行相同的操作City

于 2012-07-24T09:49:19.847 回答
1
Hello try with this syntax

IF EXISTS (SELECT * FROM Country WHERE CountryName= @CountryName)
BEGIN
    UPDATE dbo.Country
    SET CountryName = @CountryName
    WHERE   CountryId = (SELECT CountryId FROM dbo.Country WHERE CountryName= @CountryName);
END
ELSE
BEGIN
   INSERT INTO dbo.Country(CountryName) VALUES (@CountryName);

END

-- For the identity you must just add identity to your column in your creation script
于 2012-07-24T09:44:01.480 回答
0

你需要MERGE语法

http://technet.microsoft.com/en-us/library/bb510625.aspx

或在插入之前手动检查(即:使用IF EXISTS (...))是否存在国家/地区。

于 2012-07-24T09:40:12.197 回答
0

为什么不在 CountryName 列上设置唯一约束,根本不允许您插入重复的国家

于 2012-07-24T09:43:29.483 回答