Click here to Skip to main content
15,893,564 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to check the user name already exits by using stored procedure
while inserting, if the username already taken by somebody means we have to say user name aleady exists.

Here is the code

SQL
create proc sp_user
(
@userid int,
@username varchar(20)
)
as 
begin
insert into tbl_ins(userid, username) values(@userid,@username)
end


please help me...

Thanks in advance...
Posted
Updated 27-Nov-13 17:59pm
v2

create proc sp_user
(
@userid int,
@username varchar(20)
)
as 
begin
insert into tbl_ins(userid, username) values(@userid,@username)
end

This is your code, i have some suggesstion to you
1) Never create a procedure with The starting letter of SP_ see the reason here[^]
2) where is the try catch?
To answer your problem you have two way
1) Create a unique constraint(Key) on the column USername in the table tbl_ins
You don't need a extra crap code here?
2)(well some one say that i will maintain my code in my Proc only)inside the proc with extra code here
SQL
CREATE PROC sp_user (@userid INT ,@username VARCHAR (20))
AS

BEGIN
    IF EXISTS ( SELECT 1
                FROM   tbl_ins
                WHERE  UserName = @username )
    BEGIN
        RAISERROR ( 'UserName %s Already Exists.', -- Message text.
          16, -- Severity.
          1, -- State.
          @username
           );
    END
    ELSE
    BEGIN
        INSERT INTO tbl_ins
          (userid, username)
        VALUES
          (@userid, @username)
    END
END

i think now you are clear, reply me what's your solution either 1 or 2
 
Share this answer
 
v2
Comments
gvprabu 28-Nov-13 9:23am    
Nice work...
SQL
create proc sp_user
(
@userid int,
@username varchar(20)
)
as 
begin

Declare @Ucount int

Select @Ucount = Count(*) From tbl_ins where Userid = @Userid

IF @Ucount = 0
BEGIN
insert into tbl_ins(userid, username) values(@userid,@username)
Return 1
END
Else
return -1
end


From front end you can display a message
 
Share this answer
 
See this:
C#
CREATE PROCEDURE create_user
(
   @userid int,
   @username varchar(20)
)
AS
BEGIN
if exists (your query to check the existence of specified value) 
//// 
else 
 insert into tbl_ins(userid, username) values(@userid,@username)
END
 
Share this answer
 
v2
IF EXISTS(Select 1 from tbl_ins where Userid = @Userid)


sql-server-check-if-record-exists-before-insert-using-t-sql
 
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