2016年6月19日 星期日

t_sql

區域變數宣告:區域變數範圍以GO關鍵字區隔
declare @var1 as varchar(30)

declare @var2 int, @var3 datetime

賦值:

方法1:
在宣告時直接賦值,例如 declare @var1 = 'mytext'

方法2:
set @var1 = 'book store'

set@var2 = 1

set@var3 = getdate()

方法3:
select @var1 = 'mytext'

查詢:

select @var1

select @var2

select @var3

查詢結果:
book store
1
2016-.......當時日期

例1:
declare @customer

select @customer = 客戶名稱
from 客戶
where 客戶名稱 = 4

select @customer

查詢結果:
會查詢客戶資料表中客戶名稱欄位值為4的資料,並將結果存到@customer中
最後再用select @customer 指令顯示出來


系統變數:
@@+變數名稱
例:
select @@VERSION -- 查詢SQL SERVER軟體版本

select @@LANGUAGE --查詢語言

select @@ROWCOUNT --回傳最後一次查詢結果列數

於訊息標籤輸出結果:
PRINT指令

例:
PRINT 'ABC'
PRINT 'ABC' + 'DEF'
PRINT 1
PRINT 1 + 1

訊息標籤內顯示之結果:
ABC
ABCDEF
1
2


IF判斷式:
例1:

declare @x = 1

if @x >2
   PRINT '@x>2
else
   PRINT '@x<2'
GO

輸出結果:
@x<2

例2:

if (select sum(單價) from 標標公司) > 1000
    PRINT '標標公司產品總價大於1000
esle
    PRINT '標標公司產品總價小於1000
GO

if  'Windows 使用手冊' in (select 書籍名稱 from 書籍)
    PRINT '有Windows 使用手冊'
else
    PRINT '無Windows 使用手冊'
GO

if  1000 > all (select 單價 from 標標公司)
    PRINT '標標公司產品單價最高不超過1000
GO


while 迴圈:
例:

declare @id=0, @name='', @price=0, @count=1

while @id < 500
begin
    @id+=1
    select @name = 書籍名稱, @price = 單價
    from 書籍
    where bookId = @id
    if @@ROWCOUNT = 0 break
    if @price > 400 contiune
    PRINT @name
    if @count %3 =0 PRINT '------' -- 每3筆資料分隔
    @count +=1
end
GO

以上程式碼查詢400元以上的書籍名稱,在訊息標籤輸出結果


switch條件式:以CASE關鍵字觸發
例1:

declare @a =3, @answer varchar(10)

set @answer = CASE @a
    when 1 then 'a'
    when 2 then 'b'
    when 3 then 'c'
    when 4 then 'd'
    when 5 then 'e'
end
PRINT 'answer is ' + @answer
GO

輸出結果:
answer is c

例2:

select 公司名稱, 聯絡人 + case 性別
                          when '男' then '先生'
                          when '女' then '小姐'
                          else '敬啟者'
                          end as '聯絡人'
                          , 電話
from 客戶

查詢結果:
公司名稱 / 聯絡人 / 電話
    xxx公司/xxx先生/xxxxx
    xxx公司/xxx小姐/xxxxx


程式列跳躍指令GOTO:
例1:

declare @number =3
if  (@number % 3 =0)
    GOTO THREE
else
    GOTO NOTTHREE


THREE:
    PRINT '三的倍數'

GOTO THEEND

NOTTHREE:
    PRINT '不是三的倍數'


THEEND:

GO

例2:
declare @num =0

start:
select @num +=1

if @num > 10 GOTO theend
if (@num % 2 =0) GOTO even
else GOTO odd

even:
    PRINT cast(@num as char(2)) + 'is 偶數'
GOTO start
odd:
    PRINT cast(@num as char(2)) + 'is 奇數'
GOTO start

theend:

沒有留言:

張貼留言