Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable has a value in a SQL Server 2008 stored procedure

Tags:

sql

sql-server

I need to check whether a variable has a value or not.

declare @name varchar(20)

set @name = (SELECT Product_Name 
             FROM tb_new_product_Name_id 
             WHERE Product_Name = @productName)

 if (@name )   // here I need to check it 

How to do it? thanks

like image 679
Happy Avatar asked Feb 25 '14 07:02

Happy


People also ask

How do you check if a variable has a value in SQL?

So checking for value = '' or value = 0 or value is null, one of the three would check if its empty.

How do I get the value of a variable in SQL Server?

To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

How do you assign a value to a variable in SQL Server stored procedure?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

What is @@ variable in SQL?

In SQL Server, symbol @@ is prefixed to global variables. The server maintains all the global variables. We cannot declare them.


2 Answers

Try this

if (@name is null or @value = '') //it will indicate whether it contains a value or not
like image 63
Nagaraj S Avatar answered Jan 22 '23 09:01

Nagaraj S


Just do the IF directly, using EXISTS instead:

IF EXISTS(SELECT * FROM tb_new_product_Name_id 
        where Product_Name=@productName)
BEGIN
    --Do something because a row existed with that name
END

We may be able to further assist with simplifying your code if you told us more on what you were planning to do having confirmed a row existed in tb_new_product_Name_id. It looks like you're writing very procedural code - first I'll do X, then I'll do Y, then I'll do Z, etc. SQL excels as a language where you tell it "what to do" - for the entire data set you want to compute - not "how to do it" in a step by step, row by row fashion.

like image 41
Damien_The_Unbeliever Avatar answered Jan 22 '23 09:01

Damien_The_Unbeliever