Skip to content
Advertisement

T-SQL stored procedure: update local variable inside IF/ELSE statement

I have an item table that has a foreign key constraint customer_id that references a customer table. The customer_id column is of type uniqueidentifier which needs to be generated on insert (there is no value we could use for this provided by the client). I am created a T-SQL (using SQL Server Express) stored procedure to be called from C# using ADO Entity Data Model to add records to the database.

The objective is to create an item (if it doesn’t already exist) with a reference to an already existing customer record or a newly created customer record by using the declared @customer_id variable.

Below is a simplified version of my stored procedure.

This procedure works for newly created customer records, but not when referencing an existing customer record.

Attempting to add items with an existing associated customer_id throws a

SqlException: Cannot insert the value NULL into column ‘customer_id’, table ‘dbo.item’

I am fairly new to T-SQL, but this seems to be a scope issue. Any thoughts?

Advertisement

Answer

It looks like you have the wrong WHERE clause

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement