Click here to Skip to main content
15,891,828 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
SQL
create table cust
(
id int identity(1,1),
cname varchar(20),
myid varchar(50)
)

----------------------------------------------------

i want to store this in myid column automatically
SQL
select cname+''+convert(varchar(50),id) as myid from cust where id=max(id)+1

id		cname		myid
-------------------------------------------------------
1		abc		abc1
Posted
Updated 11-Oct-14 23:23pm
v3

Create a "for insert" trigger[^] on the table and place your code to "calculate" [myid] in there.

See these CP articles for more information
Triggers -- SQL Server[^]
Be Very Careful When You Write SQL Trigger[^]
SQL:Target a Trigger[^]
 
Share this answer
 
Comments
Maciej Los 12-Oct-14 15:21pm    
Good one, +5!
Please, see my answer ;)
I'd suggest you to use stored procedure.

SQL
CREATE PROCEDURE uspNewCustomer
    @custname NVARCHAR(50)
BEGIN
    DECLARE @myid INT = 0 --in case of error, return zero

    INSERT INTO Customers (CustomerName) VALUES(@custname)
    SET @myid = @@IDENTITY()

    UPDATE Customers SET MyID = CustomerName + CONVERT(VARCHAR(10), @myid)

    --RETURN newely inserted value
    SELECT @myid

END 


For further information, please see:
Table Column Properties (SQL Server Management Studio)[^]
CREATE PROCEDURE[^]
Specify Default Values for Columns[^]
@@IDENTITY[^]
Return Data from a Stored Procedure[^]
 
Share this answer
 
Comments
vijay_d_b 13-Oct-14 4:48am    
thanx 4 ur reply ,i tried like this n working fine ,let me know is it correct way.
CREATE PROCEDURE uspNewCustomer

@cname VARCHAR(50)
AS
BEGIN
declare @id int
DECLARE @myid int
INSERT INTO cust(cname)values(@cname)


UPDATE cust SET myid = cname+''+convert(varchar(10),isnull(id,0))

SELECT (cname+''+convert(varchar(10),isnull(id,0))) as myid from cust
END
Maciej Los 13-Oct-14 4:53am    
Why to use last select statement, if the value of myID has been already added to the table (via UPDATE statement)?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900