Search notes:

SQL Server - T-SQL / variables - declare

The declare statement is needed to associate a variable with a data type or to define a cursor.

Scope

Variables that are declared within a begin … end block are visible outside that block:
declare @flag varchar(10) = 'yes';

if @flag = 'yes' begin
   declare @var_yes varchar(10) = 'tq84 yes';
end
else begin
   declare @var_no  varchar(10) = 'tq84 no';
end;

print 'var_yes = ' + coalesce(@var_yes, 'n/a');
print 'var_no  = ' + coalesce(@var_no , 'n/a');
Github repository about-MSSQL, path: /t-sql/variables/declare/scope.sql
However, the scope of a variable ends with a go.

Declare and assign a select statement's result

It's possible to declare a variable and assign the result of a select statement in one go:
set nocount on

create table tq84_some_values (val integer);

insert into tq84_some_values values (11);
insert into tq84_some_values values ( 5);
insert into tq84_some_values values (42);
insert into tq84_some_values values (31);
insert into tq84_some_values values (27);

--
-- declare a variable and assign a value from
-- a select statement:
--
declare @min_val integer = (select min(val) from tq84_some_values);

print('min_val = ' + str(@min_val));

drop table tq84_some_values ;
Github repository about-MSSQL, path: /t-sql/variables/declare/declare-and-select.sql

See also

T-SQL

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1740452760, '3.137.174.186', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/databases/SQL-Server/T-SQL/variables/declare/index(81): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78