Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - Assign value from query to variable if record exists in a single select

How I can improve below code to use 'select' only once?

IF EXISTS (SELECT [NUMBER] FROM [TABLE] WHERE [ID_RECORD] = @id_record
BEGIN
   DECLARE @tmp_variable
   SELECT @tmp_variable = [NUMBER] FROM [TABLE] WHERE [ID_RECORD] = @id_record

   SET @other_variable = @tmp_variable
END
ELSE
BEGIN
   SET @other_variable = 0
END
like image 538
rgb Avatar asked May 16 '13 07:05

rgb


People also ask

How do you assign a value from a SELECT statement to a variable in SQL?

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 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.

How do I SELECT only certain values in a column in SQL?

The column names that follow the select keyword determine which columns will be returned in the results. You can select as many column names that you'd like, or you can use a “*” to select all columns. The table name that follows the keyword from specifies the table that will be queried to retrieve the desired results.


1 Answers

Try This :

 DECLARE @tmp_variable INT
 SET @tmp_variable = ISNULL(( SELECT    [NUMBER]
                              FROM      [TABLE]
                              WHERE     [ID_RECORD] = @id_record
                             ), 0)
like image 65
Behrouz Bakhtiari Avatar answered Nov 14 '22 05:11

Behrouz Bakhtiari