简体   繁体   中英

Inserting record from one column to another column in the same scope or statement

I have a Stored Procedure that populates a table: This table as indicated in the code below has an identity column which is also the primary key column.

I would like to append the primary key to contain leading letters: Example: ABC123. Obviously this is not possible because the Primary key column is INT datatype.

So I created an additional column so that I can insert the appended primary key. This works except I have to make the new column Null and I am using an UPDATE statement.

Something tells me there is a better way.

Is there a way I can do this without using UPDATE after the initial Insert and have the new column CategoryID as Not Null ?

Table Code:

CREATE TABLE [dbo].[Registration] (
    [SystemID]   INT          IDENTITY (100035891, 1) NOT NULL,
    [CategoryID] CHAR (13)    NULL,
    [FName]      VARCHAR (30) NOT NULL,
    [LName]      VARCHAR (30) NOT NULL,
    [MInit]      CHAR (1)     NULL,
    PRIMARY KEY CLUSTERED ([SystemID] ASC)
);

Stored Procedure:

CREATE PROCEDURE [dbo].[uspInsertRegistration]

@FName VARCHAR(30),
@LName VARCHAR(30),
@MInit CHAR(1),
@CategoryID CHAR(13),
@SystemID int OUTPUT

AS
BEGIN
SET NOCOUNT ON
DECLARE @ErrCode int

INSERT INTO [dbo].[Registration] ([FName],[LName],[MInit])
  VALUES (@FName, @LName, @MInit)

SELECT @ErrCode = @@ERROR, @SystemID = SCOPE_IDENTITY()

UPDATE [dbo].[Registration]
SET CategoryID = 'ABC'+ CAST(SystemID AS CHAR)

SET NOCOUNT OFF
RETURN @ErrCode
END

Finally this is what the table looks like with the data:

在此输入图像描述

Thanks for being contagious with your knowledge. :)

Guy

My suggestion is to use a computed column, as what you're trying to do introduces redundancy. See below:

http://msdn.microsoft.com/en-us/library/ms191250%28v=sql.105%29.aspx

Alternately, make it big enough to contain a GUID, put a GUID into the column on the insert, then update it afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM