3

DDL:

CREATE TABLE [dbo].[Admin_Profile](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Ad_Regid]  AS ('R'+right('200'+CONVERT([varchar](10),[ID],(0)),(6))) PERSISTED NOT NULL,
    [Ad_Fname] [varchar](25) NULL,
    [Ad_Lname] [varchar](25) NULL,

 CONSTRAINT [PK_Admin_Profile] PRIMARY KEY CLUSTERED 
(
    [Ad_Regid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SP:

create procedure _insertAdminProfile
(
    @Ad_Fname varchar(25),
    @Ad_Lname varchar(25),
    @Ad_Pwd varchar(7) Out
    as 

    Begin

    insert into dbo.Admin_Profile (Ad_Fname,Ad_Lname) values (@Ad_Fname,@Ad_Lname);

    SELECT ISNULL(MAX(@Ad_Pwd), 0) + 1 FROM dbo.Admin_Profile

    end

我尝试了很多方法来获取 insert.Ad_Regid... 的输出...没有得到,我也尝试了 select @Ad_Regid = SCOPE_IDENTITY()

谢谢...

4

3 回答 3

2

您需要使用该OUTPUT子句:

DECLARE @OutputValues TABLE (ID INT, RegID VARCHAR(7))

INSERT INTO dbo.Admin_Profile (Ad_Fname, Ad_Lname) 
OUTPUT Inserted.Id, Inserted.Ad_RegId INTO @OutputValues(ID, RegID)
VALUES(@Ad_Fname, @Ad_Lname);

运行插入语句后,您将在表变量中包含所有插入的值ID和相应的值Ad_RegId@OutputValues

SELECT ID, RegID FROM @OutputValues

在 SQL Server 联机丛书中阅读有关该子句的更多信息OUTPUT

于 2013-07-05T07:02:39.553 回答
1

根据您的选择尝试这三种变体 -

1:

CREATE PROCEDURE _insertAdminProfile
(
     @Ad_Fname VARCHAR(25),
     @Ad_Lname VARCHAR(25),
     @Ad_Pwd VARCHAR(7) OUTPUT
)
AS BEGIN

     INSERT INTO dbo.Admin_Profile (Ad_Fname, Ad_Lname)
     VALUES (@Ad_Fname, @Ad_Lname)

     SELECT @Ad_Pwd = [Ad_Regid]
     FROM dbo.Admin_Profile
     WHERE [ID] = SCOPE_IDENTITY()

END

2:

CREATE PROCEDURE _insertAdminProfile
(
     @Ad_Fname VARCHAR(25),
     @Ad_Lname VARCHAR(25),
     @Ad_Pwd VARCHAR(7) OUTPUT
)
AS BEGIN

     INSERT INTO dbo.Admin_Profile (Ad_Fname, Ad_Lname)
     VALUES (@Ad_Fname, @Ad_Lname)

     SELECT @Ad_Pwd = 'R' + RIGHT('200'+CONVERT(VARCHAR(10),SCOPE_IDENTITY(),0), 6)

END

3:

CREATE PROCEDURE _insertAdminProfile
(
     @Ad_Fname VARCHAR(25),
     @Ad_Lname VARCHAR(25),
     @Ad_Pwd VARCHAR(7) OUTPUT
)
AS BEGIN

     DECLARE @MyTableVar TABLE (Ad_Pwd VARCHAR(7));

     INSERT INTO dbo.Admin_Profile (Ad_Fname, Ad_Lname)
     OUTPUT INSERTED.Ad_Regid INTO @MyTableVar
     VALUES (@Ad_Fname, @Ad_Lname)

     SELECT @Ad_Pwd = Ad_Pwd
     FROM @MyTableVar

END
于 2013-07-05T06:33:56.510 回答
0

您是否尝试过使用全局变量@@IDENTITY?

CREATE PROCEDURE _insertAdminProfile
(
     @Ad_Fname VARCHAR(25),
     @Ad_Lname VARCHAR(25),
     @ident NUMERIC OUT
)
AS BEGIN

     INSERT INTO dbo.Admin_Profile (Ad_Fname, Ad_Lname)
     VALUES (@Ad_Fname, @Ad_Lname);

     SET @ident = @@IDENTITY;

END
于 2013-07-05T06:39:08.267 回答