0

我有一个创建用户配置文件的存储过程,我的表单具有以下字段:

FirstName,
LastName.
EmailAddress,
ZipCode,
Password

邮政编码是我的 UserProfile 中的一个 FK,类型为 smallint,该值可能存在也可能不存在于名为的表中Location

LocationId bigInt (identity index)
ZipCode smallint

有没有办法从我的存储过程中查询该表,如果该项目存在,则在我的存储过程中使用该条目的 PK 吗?

到目前为止,这是我的存储过程

CREATE PROCEDURE [dbo].[SP_InsertInitialProfile]

@FirstName          NVARCHAR(1000),
@LastName           NVARCHAR(1000),
@EmailAddress       NVARCHAR(1000),
@ZipCode            SMALLINT,
@Password           NVARCHAR(1000)

AS

IF (SELECT COUNT(1) FROM UserProfile WHERE EmailAddress =@EmailAddress) = 1
BEGIN
    RETURN -1 
END ELSE
BEGIN
    INSERT INTO UserProfile(FirstName,LastName,EmailAddress,Password)
    VALUES(@FirstName,@LastName,@EmailAddress,@Password)

    RETURN  Cast(@@IDENTITY as INT)
END
4

1 回答 1

1

你可以像这样做SP:

           CREATE PROCEDURE [dbo].[SP_InsertInitialProfile]

            @FirstName          NVARCHAR(1000), 
            @LastName           NVARCHAR(1000), 
            @EmailAddress       NVARCHAR(1000), 
            @ZipCode            SMALLINT, 
            @Password           NVARCHAR(1000)  

            AS 

             varCountNbr number;

            BEGIN

               SELECT COUNT(1) INTO varCountNbr
               FROM 
                  Location
               WHERE 
                 ZipCode=@ZipCode;

               IF  varCountNbr = 0
                     INSERT @ZipCode INTO Location TABLE;
              -- You have to commit here, in order to have the PK value exists.
                     COMMIT;

               INSERT INTO USERPROFILE TABLE;

               COMMIT;


            END;
于 2012-10-08T23:15:45.340 回答