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