sql server 存储过程学习

本文介绍了SQL Server中如何定义和使用游标,包括声明游标、打开游标、提取数据、关闭游标以及删除游标的过程。fetch语句用于在活动集中移动游标并获取相应行的数据,@@FETCH_STATUS则用于检查fetch操作的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.站点表里添加、更新数据

create PROCEDURE [dbo].[EDIT_STORE]
--定义一些变量
    @storeName nvarchar(50),
    @storeUrl nvarchar(50),
    @storeId int=null
AS
if(@storeId is null)
    begin
        update store set store_name=@storeName,store_url=@storeUrl where store_id=@storeId
    end
else
    if(exists (select store_id from store where store_url = @storeUrl))

    begin

--赋值
        set @storeId=(select top 1 store_id from store where store_url = @storeUrl)
        update store set store_name=@storeName,store_url=@storeUrl where store_id=@storeId
    end
    else
    begin
        insert into store (store_name,store_url) values (@storeName,@storeUrl)

    end


定义与使用游标的语句

    declare :
        declare  游标名[scroll]  cursor  for select语句[for update [of列表名]]
        定义一个游标,使之对应一个select语句
       for update任选项,表示该游标可用于对当前行的修改与删除
    open
       打开一个游标,执行游标对应的查询,结果集合为该游标的活动集
       open  游标名
    fetch
       在活动集中将游标移到特定的行,并取出该行数据放到相应的变量中
       fetch [next | prior | first | last | current | relative n | absolute m] 游标名into  [变量表]
    close
       关闭游标,释放活动集及其所占资源。需要再使用该游标时,执行open语句
       close  游标名
    deallocate
       删除游标,以后不能再对该游标执行open语句
       deallocate游标名
    @@FETCH_STATUS
        返回被FETCH语句执行的最后游标的状态.
       0 fetch语句成功
        -1 fetch语句失败
        -2 被提取的行不存在



游标的例子:
ALTER proc [dbo].[cusorInsert] @pId varchar(50) as
--局部变量 declare @id int
--声明游标 declare cur cursor for select product_category_id from product_category
--打开游标 open cur fetch next from cur into @id
--游标状态 0表示成功,用while循环 
while @@FETCH_STATUS=0 
begin 
insert into product(product_id,product_name,primary_product_category,product_length, product_width,product_height,product_weight,created_stamp,updated_stamp) 
values(@pId+ convert(varchar(30),@id),'ss',null,1,1,1,1,GETDATE(),GETDATE()) 
fetch next from cur into @id end
--关闭游标 close cur
--删除游标 deallocate cur












                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值