Patrick Winchester
Patrick Winchester

Reputation: 31

SQL IF ELSE Statement

I'm creating an Insert Query in C# WinForms, to INSERT members into a database table (Members).
I'm using this code:

IF NOT EXISTS(SELECT * FROM Members WHERE PersonalId = @PersonalId)
BEGIN
INSERT INTO Members (PersonalId, FirstName, LastName, City, PhoneNumber)
VALUES (@PersonalId, @FirstName, @LastName, @City, @PhoneNumber)
END 

(@PersonalId, should have the value that the user types in the textbox?)

This pop up :

enter image description here

Any help ?

Upvotes: 0

Views: 202

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062600

That suggests you are missing a parameter. You should have something like:

cmd.Parameters.AddWithValue("PersonalId", personalId);

where (importantly) personalId is not null (it can be DBNull.Value, though).

(@PersonalId, should have the value that the user types in the textbox?)

It probably should, but it sounds like you haven't added it correctly.

Upvotes: 3

walther
walther

Reputation: 13600

Why would you do that?? Instead of this thing simply define the column as Unique or maybe even better as a Primary key (if your table doesn't already have a PK).
After you've done it, your SQL server will take care of it, because if the column is marked as unique or PK, it won't allow other items to have the same value in the column.

There's really no need to put this logic into every SQL insert...

Your error says one thing - you haven't defined the parameter @PersonalId, but I think it's a bad way to take..

Upvotes: 0

Related Questions