取代游標的方案

2021-04-01 05:44:24 字數 1910 閱讀 4238

----使用min()函式或max()函式--------------------

declare @emp_id varchar(15),@name varchar(50),@job_id int,@hire_date datetime

set @emp_id=(select min(emp_id) from pubs.dbo.employee where minit is not null)

while 1=1

begin

select @name=fname+lname,@job_id=job_id,@hire_date=hire_date from pubs.dbo.employee where emp_id=@emp_id

print @name+' , '+cast(@job_id as varchar(5))+' , '+convert(varchar(10),@hire_date,20)

select @emp_id=min(emp_id) from pubs.dbo.employee where minit is not null and emp_id>@emp_id

if @emp_id is null break

end-----用表函式------------

declare @count int,@n int,@emp_id varchar(15),@name varchar(50),@job_id int,@hire_date datetime

declare @employee table(

id int identity(1,1),

emp_id varchar(15),

name varchar(50),

job_id int,

hire_date datetime

)insert @employee

select emp_id,fname+lname as name,job_id,hire_date from pubs.dbo.employee where minit is not null

set @n=1

set @count=(select max(id) from @employee)

while @n<=@count

begin

select @name=name,@job_id=job_id,@hire_date=hire_date from @employee where id=@n

print @name+' , '+cast(@job_id as varchar(5))+' , '+convert(varchar(10),@hire_date,20)

set @n=@n+1

end------使用臨時表-------------------

declare @count int,@n int,@emp_id varchar(15),@name varchar(50),@job_id int,@hire_date datetime

select identity(int,1,1) as id,emp_id,fname+lname as name,job_id,hire_date into #t from pubs.dbo.employee where minit is not null

set @n=1

set @count=(select max(id) from #t)

while @n<=@count

begin

select @name=name,@job_id=job_id,@hire_date=hire_date from #t where id=@n

print @name+' , '+cast(@job_id as varchar(5))+' , '+convert(varchar(10),@hire_date,20)

set @n=@n+1

enddrop table #t

MSSQL一種取代游標的方案

原文 mssql一種取代游標的方案 declare 欄位1 資料型別 declare 欄位2 資料型別 declare tmp while id int select tmp while id identity int,1,1 tmp while flag 0,欄位1 欄位2 into tmp wh...

Cursor游標(游標)的使用

為了處理sql語句,oracle 將在記憶體中分配乙個區域,這就是上下文區。這個區包含了已經處理完的行數 指向被分析語句的指標,整個區是查詢語句返回的資料行集。游標就是指向上下文區控制代碼或指標。兩種游標 一 顯示游標 需要明確定義!顯示游標被用於處理返回多行資料的select 語句,游標名通過cu...

游標的使用

declare sql varchar 8000 password varchar 200 密碼 tbname varchar 500 資料庫.dbo.表名,如果不指定 dbo.表名,則匯出資料庫的所有使用者表 filename varchar 1000 匯入 匯出路徑 檔名,如果 tbname引數...