Click here to Skip to main content
15,904,823 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello all

i want to insert code in my coloum using store procedure like this : BCA110000000001
where BCA is code from user input
11 is year now

how i can do this??
Posted
Comments
Bun Leap_kh 6-Oct-11 23:21pm    
What is 0000000001? auto number?
gunkrr 6-Oct-11 23:23pm    
yes thats autonumber, buti can handle that

thank you for all

i have done it :)
 
Share this answer
 
You can check the following store procedure
CREATE PROCEDURE [dbo].[Check]
	@UserInput nvarchar(50),
	@Last int
AS
DECLARE @Result nvarchar(20)
DECLARE @pad_characters VARCHAR(10)



SET @pad_characters = '0000000000'


SET @Result = @UserInput+SUBSTRING(convert(nvarchar,Datepart(Year,getdate())) ,3 ,2)+ RIGHT(@pad_characters+convert(nvarchar(10),@Last),10)


SeLECT @Result

Exec [dbo].[Check] 'BCA ',1


Hope be helpful,
Theingi Win
 
Share this answer
 
FLetz assume the key column (BCA11000000001) name as DataKey. Letz create the table as:
SQL
CREATE TABLE dbo.MyTable
(
    DataKey int NOT NULL PRIMARY KEY,
    OtherKey varchar(50),
    ....
) 



SQL maintains DataKey column as identity primary column, starting from 1. Expected key is constructed using SELECT command as:

SQL
SELECT 'BCA'+ substring(year(getdate()),1,2) + Cast(Datakey as varchar(10)


It will result the expected code BCA11000000001
 
Share this answer
 
Comments
gunkrr 6-Oct-11 23:35pm    
Argument data type int is invalid for argument 1 of substring function.

whats that??
Ganesan Senthilvel 6-Oct-11 23:47pm    
You can cast the current year as:
substring(Cast(year(getdate()) as varchar(4)),1,2)
gunkrr 7-Oct-11 0:16am    
this code catch year as 20 not 11
let test this:
SQL
Create Procedure InsertData @code varchar(50)
As
Begin
    Declare @year varchar(2)
    Declare @number int
    Declare @formatedNumber varchar(20)
    Declare @value varchar(50)
    Select @number=MAX(CAST(RIGHT(code,10) As int)) from TableName
    Set @number=ISNULL(@number,0) + 1
    Set @formatedNumber=RIGHT('000000000'+CAST(@number as varchar(10)),10)
    Set @year=RIGHT(CAST(YEAR(GETDATE()) As varchar(4)),2)
    Set @value=@code + @year + @formatedNumber
    Insert into TableName(code) values(@value)
End
 
Share this answer
 
v3
Comments
gunkrr 6-Oct-11 23:25pm    
Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query.

how convert that??
Bun Leap_kh 6-Oct-11 23:34pm    
it missed function YEAR().
gunkrr 6-Oct-11 23:55pm    
where using function YEAR() ??
Bun Leap_kh 7-Oct-11 2:44am    
at line 11
gunkrr 7-Oct-11 2:46am    
thank you, i have done it :)

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