将数据插入3个表的存储过程。不工作。

时间:2012-07-24 09:39:11

标签: sql-server-2008

我有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

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

我是怎么做到的?我的SP会因每次插入而发生变化。

4 个答案:

答案 0 :(得分: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

如果需要,您可以对StateCity执行相同操作

答案 1 :(得分: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

答案 2 :(得分:0)

您需要MERGE语法

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

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

答案 3 :(得分:0)

为什么不在CountryName列上设置Unique Constraint,不允许您插入重复的国家/地区