none
Comparing 2 values in same column SQL (C#) RRS feed

  • Question

  • Hi all. I am busy writing a program, in Microsoft Visual Web Developer, and have a database was several tables. The one I am focusing on now is the ACCOUNT table. This table contains username, password and email column. 

    I want to compare a username entered into a textbox with the existing usernames in the ACCOUNT table, so that I can create a message saying that the entered user already exists.

    I know how to do this in C# with if statements, but am really unsure with SQL, since not sure how to use it with SELECT.Thanks


    Saturday, May 11, 2013 3:19 PM

Answers

  • I Would create a stored procedure as follows, and execute it from the application.

    CREATE PROCEDURE IsValidUserName
    (
    	@UserName VARCHAR(100)
    )
    AS
    IF EXISTS (SELECT * FROM ACCOUNT WITH(NOLOCK) WHERE UserName=@UserName)
    BEGIN	
    	SELECT 0 AS IsValid -- Name exists
    END ELSE BEGIN
    	SELECT 1 AS IsValid -- Name is unique
    END

    The application can look at the result and decide whether the name is unique or not.

    The code above is just a template and you may need to make necessary changes to fit this into your specific application needs.


    My Blog


    Saturday, May 11, 2013 5:16 PM