sqlserver 局部變量的使用
更新時間:2010年06月24日 00:56:17 作者:
在SQL中我們或許會使用到局部變量的問題,下面給出微軟的兩個小例子
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
@find就是一個局部變量。
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)
下例使用名為 @find 的局部變量檢索所有姓以 Ring 開頭的作者信息。
復制代碼 代碼如下:
Use pubs
declare @find varchar(30)
set @find='Ring%'
select au_lname,au_fname,phone
from authors
where au_lname like @find
@find就是一個局部變量。
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)
相關文章
MSSQL報錯:參數(shù)數(shù)據(jù)類型 text 對于 replace 函數(shù)的參數(shù) 1 無效的解決辦法
在sql中使用replace函數(shù)可以替換某個字段中的一些內容,但是如果字段是text類型那么使用replace函數(shù)就會報“參數(shù)數(shù)據(jù)類型text 對于replace 函數(shù)的參數(shù)1 無效?!?,這個錯誤說明對text或ntext類型的數(shù)據(jù)在查詢中不能進行字符串操作2014-03-03