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
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.
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.
Try This :
DECLARE @tmp_variable INT
SET @tmp_variable = ISNULL(( SELECT [NUMBER]
FROM [TABLE]
WHERE [ID_RECORD] = @id_record
), 0)
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