SQL Server(六)——索引、視圖和SQL編程

來源:互聯網
上載者:User

標籤:

1.索引

添加索引,設計介面,在任何一列前右鍵--索引/鍵--點擊進入添加某一列為索引

2.視圖

視圖就是我們查詢出來的虛擬表

建立視圖:create view 視圖名          

              as          

              SQL查詢語句,分組,排序,in 等都不能寫

視圖的用法: select * from 視圖名

3.SQL編程

(1)定義變數:declare @變數名 資料類型    

         例:declare @a int

(2)變數賦值:set @變數名 = 值     

         例:set @a=10

set @a = 10  --賦值,不列印

select @a;  --列印在結果集中

print @a;   --列印在訊息框中

-----------------------------------------------------

例1、查汽車表中名稱含有寶馬兩個字的

declare @name varchar(20) set @name=‘寶馬‘ select * from car where Name like ‘%‘+@name+‘%‘
View Code

例2、查汽車表中所有汽車的平均值並輸出

declare @price decimal(10,4) select @price = AVG(Price) from Car print ‘所有汽車的平均價格為:‘+cast(@price as varchar(20))
View Code

-----------------------------------------------------

(3)if ... else 的用法,if後面沒有小括弧,花括弧用begin end 替代

if 判斷條件

begin   

要執行的語句

end

else

begin   

要執行的語句

end

例:

declare @a int declare @b int declare @c intset @a =10; set @b =5;if @a>@b begin  set @c = @a + @b; end else begin  set @c = @a - @b; end print @c 
View Code

-----------------------------------------------------

(4)C#裡的Switch case 變形到資料庫裡用法

declare @ccname varchar(20) set @ccname = ‘寶馬‘ select * from Car where Name likecase --switch...case的開頭 when @ccname=‘寶馬‘ then ‘%寶馬%‘ when @ccname=‘奧迪‘ then ‘%奧迪%‘ else ‘%‘ end --switch...case的結尾
View Code

-----------------------------------------------------

(5)迴圈: 注意迴圈四要素

declare @str varchar(20) set @str = ‘你好‘ declare @i int set @i = 1while @i<=10 begin  print @str + cast (@i as varchar(20))  set @i = @i + 1 end
View Code

whie(條件) {  迴圈體 }

-----------------------------------------------------

注意:語句結束之後不要寫分號或逗號例

SQL Server(六)——索引、視圖和SQL編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.