SqlServer中循環和條件語句示例!


-- ╔════════╗
-- =============================== ║ if語句使用示例 ║
-- ╚════════╝
declare @a int
set @a=12
if @a>100
begin
print @a
end
else
begin
print 'no'
end
-- ╔══════════╗
-- =============================== ║ while語句使用示例 ║
-- ╚══════════╝
declare @i int
set @i=1
while @i<30
begin
insert into test (userid) values(@i)
set @i=@i+1
end

-- 設置重復執行 SQL 語句或語句塊的條件。只要指定的條件為真,就重復執行語句。可以使用 BREAK 和 CONTINUE 關鍵字在循環內部控制 WHILE 循環中語句的執行。 本條為以前從網上查找獲取!


-- ╔════════╗
-- ================================ ║ 臨時表和try ║
-- ╚════════╝

-- 增加臨時表
select * into #csj_temp from csj

-- 刪除臨時表 用到try
begin try -- 檢測代碼開始
drop table #csj_temp
end try

begin catch -- 錯誤開始
end catch


-- ╔═════════╗
-- =============================== ║ 游標循環讀記錄 ║
-- ╚═════════╝

declare @temp_temp int
--declare @Cur_Name
--@Cur_Name="aaa"
--------------------------------- 創建游標 --Local(本地游標)
DECLARE aaa CURSOR for select House_Id from House_House where Deleted=0 or deleted is null
----------------------------------- 打開游標
Open aaa
----------------------------------- 遍歷和獲取游標

fetch next from aaa into @temp_temp
--print @temp_temp
while @@fetch_status=0
begin
--做你要做的事
select * from House_monthEnd where House_Id=@temp_temp

fetch next from aaa into @temp_temp -- 取值賦給變量

--
end

----------------------------------- 關閉游標
Close aaa
----------------------------------- 刪除游標
Deallocate aaa
--

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM