DECLARE @local_variable
在批处理或过程的正文中用 DECLARE 语句声明变量,并用 SET 或 SELECT 语句给其指派值。游标变量可通过该语句声明,并且可用在其它与游标相关的语句中。所有变量在声明后均初始化为 NULL。
A. 使用 DECLARE
下例使用名为 @find 的局部变量检索所有姓以 Ring 开头的作者信息
USE pubs
DECLARE @find varchar(30)
SET @find = 'Ring%'
SELECT au_lname, au_fname, phone
FROM authors
WHERE au_lname LIKE @find

下面是结果集:
au_lname                                au_fname              phone        
-------------------------------------- -------------------- ------------
Ringer                                  Anne                  801 826-0752
Ringer                                  Albert                801 826-0752
(2 row(s) affected)

B. 在 DECLARE 中使用两个变量
下例从 Binnet & Hardley (pub_id = 0877) 的雇员中检索从 1993 年 1 月 1 日起所雇佣的雇员名称。
USE pubs
SET NOCOUNT ON
GO
DECLARE @pub_id char(4), @hire_date datetime
SET @pub_id = '0877'
SET @hire_date = '1/01/93'
-- Here is the SELECT statement syntax to assign values to two local
-- variables.
-- SELECT @pub_id = '0877', @hire_date = '1/01/93'
SET NOCOUNT OFF
SELECT fname, lname
FROM employee
WHERE pub_id = @pub_id and hire_date >= @hire_date
下面是结果集:
fname                 lname                          
-------------------- ------------------------------
Anabela               Domingues                      
Paul                  Henriot                        
(2 row(s) affected)