Click here to Skip to main content
15,899,474 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
Hello i have a table called ElectricityDailyMeterReadings which has a column called MachineID..
I am trying to enter machine ID as M001, M002, M003 ..etc.. Normally i have used integer values for my primary keys and i used simple incremental methods for auto increments

example,

SQL
UPDATE mytable
  SET logins = logins + 1
  WHERE id = 12



But since this is a string i want to know how to write it.. Thank You
Posted

Customization needed, that's it. Below one has few samples what do you want.
Custom Auto-Generated Sequences with SQL Server[^]
 
Share this answer
 
You can do it this way suppose the table name is mytable
SQL
create table mytable(
id varchar(6) primary key,
name varchar(30),
someint int identity(0,1)
);

for this create a trigger which looks something like this
SQL
create trigger [dbo].[dummy]
on [dbo].[mytable]
for insert 
as
declare @id varchar(6);
declare @someint int;
select @id=id from inserted;
select @someint=someint from inserted;
if(@someint<10)
begin
update mytable
set id='M'+'00'+convert(varchar,@someint) where id=@id
end
else
if(@someint>=10 and @someint<100)
begin
update mytable
set id='M'+'0'+convert(varchar,@someint) where id=@id
end
else 
if(@someint>=100 and @someint<1000)
begin
update mytable
set id='M'+convert(varchar,@someint) where id=@id
end
else-- Since the transaction exceeds the limit so rollback the transation
rollback

I think this must solve your question
 
Share this answer
 
v3
The solution i have told above is good but i have found a better way to deal with your problem as i felt that execution time taken in the previous case will be bit more.
As mentioned above suppose i have a table named mytable which is like
SQL
create table mytable(
id varchar(6) primary key,
name varchar(30),
someint int identity(0,1)
);

now for this i create a trigger like this
SQL
create trigger [dbo].[dummy1]
on [dbo].[mytable]
for insert 
as
declare @id varchar(6);
declare @someint int;
select @id=id from inserted;
select @someint=someint from inserted;
update mytable
set id='M'+right('000'+convert(varchar,@someint),3) where id=@id

This works fine
 
Share this answer
 
SQL
declare @temp table
(
Id int identity(1,1),
Pid as case  len(Id) when 1 then 'M'+'000'+convert(varchar,ID)
when 2 then 'M'+'000'+convert(varchar,ID)
else 'M'+convert(varchar,ID)
end
)

insert into @temp default values

select * from @temp
 
Share this answer
 
Comments
Rakshith Kumar 12-Nov-13 0:17am    
I dont think this will give desired result
 
Share this answer
 

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