--局部臨時表:
--臨時表的表名有一個前綴#
--臨時表只對當前會話有效,只要將連接斷開,再次打開則臨時表就沒有了。
--如果臨時表是在存儲過程中創建的,則當存儲過程執行完畢,則自動銷毀。類似于c#變量的作用域范圍。
--
--全局臨時表:
--前綴##
--多個會話中可以共享全局臨時表
--只有創建該表的會話斷開時才會刪除全局臨時表,如果這時,正有其他會話在訪問該臨時表,則會等待該會話結束后刪除臨時表。
create table #student
(
?username nvarchar(10),
?age int
)
create table ##quanjustudent
(
? username nvarchar(10),
? age int
)
--表變量
declare @T1 table(c1 int,c2 int);
insert into @t1 values(1,2)
select * from @t1
--在視圖中的查詢語句,必須為每一列建一個列名
create view vw1
as
select
tsname,
case
? when tsage>50 then '豆蔻年華'
?else '青壯年'
end as '外號'
from tblstudent
select * from vw1
--在視圖中不能使用order by語句。除非:除非另外還指定了 TOP 或 FOR XML
--錯誤的寫法
create view vw2
as
select * from tblstudent order by tsid desc
--正確的寫法
create view vw2
as
select top 10 * from tblstudent order by tsid desc
--=======聲明變量----
declare @name varchar(10)
declare @age int
set @name='abc'
set @age=1
print @name
print @age
declare @userAge int
-------------=使用set與select為變量賦值的區別============
--當使用set為變量賦值時,如果右邊返回多個值,則“報錯”。
?set @userAge=(select tsage from TblStudent)
?print @userAge
declare @userAge int
?--當使用select為變量賦值時,如果右邊返回多個值,則始終以最后一個為準
?select top 5? @userAge=tsage from TblStudent
?print @userAge
declare @age int
?--一開始變量沒有賦值的時候為null,null與任何類型計算得到的結果還是null
?--所以和建議聲明變量的時候一定要賦初值。
?set @age=@age+1
?select @age --所以這里輸出還是null
----------事務--
begin tran
declare @sum int
update bank set salary=salary+1000 where id=1
set @sum+=@@error
update bank set salary=salary-1000 where id=2
set @sum+=@@error
if @sum<>0
begin
-- 回滾
? rollback
end
else
begin
--提交
? commit tran
end
--隱式事務
SET IMPLICIT_TRANSACTIONS? ON
--關閉數據庫的隱式提交
SET IMPLICIT_TRANSACTIONS? OFF
------------存儲過程-----------
---分頁存儲過程
create proc fenye
@size int,
@index int,
@total int output
as
? select * from?
(
? select *, row_number() over(order by tsid) as number from tblstudent
)as T
where T.tsid between (@index-1)*@size+1 and @index*@size
select @total=count(1) from tblstudent
declare @cont int
exec fenye 2,2,@cont output
print @cont
?
--sql server中的觸發器是表級觸發器,無論刪除多少行或者插入多少行,只觸發一次。
--是按語句來觸發的,每次執行一次語句,觸發一次觸發器。
--不會每一條語句都觸發
create trigger tri_tblclass_insert_after
on tblclass after insert
as
declare @classid int
declare @classname varchar(20)
select @classid=tclassid,@classname=tclassname from tblclass
print @classid
print @classname
insert into tblclass values('你懂的','還能有啥哇')
--當使用instead of 觸發器以后,原來的刪除操作被替換成了:
--insert into TblClassBak select * from deleted
create trigger tri_TblClass_delete_instead_of
on TblClass instead of delete
as
begin
?
?insert into TblClassBak
?select * from deleted
end
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
