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
So checking for value = '' or value = 0 or value is null, one of the three would check if its empty.
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.
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.
In SQL Server, symbol @@ is prefixed to global variables. The server maintains all the global variables. We cannot declare them.
Try this
if (@name is null or @value = '') //it will indicate whether it contains a value or not
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With