資料庫ms SQL常用語句二

來源:互聯網
上載者:User

-------------轉換函式---------------------------------------------------------
print cast(123 as varchar(20))+'abc'

print convert(varchar(20),123)+'abc'

print str(123)+'abc'


文法
使用 CAST:

CAST ( expression AS data_type )

使用 CONVERT:

CONVERT (data_type[(length)], expression [, style])

參數
expression

是任何有效 Microsoft? SQL Server? 運算式。有關更多資訊,請參見運算式。

data_type

目標系統所提供的資料類型,包括 bigint 和 sql_variant。不能使用使用者定義的資料類型。有關可用的資料類型的更多資訊,請參見資料類型。

length

nchar、nvarchar、char、varchar、binary 或 varbinary 資料類型的選擇性參數。

style

日期格式樣式,藉以將 datetime 或 smalldatetime 資料轉換為字元資料(nchar、nvarchar、char、varchar、nchar 或 nvarchar 資料類型);或者字串格式樣式,藉以將 float、real、money 或 smallmoney 資料轉換為字元資料(nchar、nvarchar、char、varchar、nchar 或 nvarchar 資料類型)。

SQL Server 支援使用科威特演算法的阿拉伯樣式中的資料格式。

在表中,左側的兩列表示將 datetime 或 smalldatetime 轉換為字元資料的 style 值。給 style 值加 100,可獲得包括世紀數位的四位年份 (yyyy)。




使用帶有 LIKE 子句的 CAST
下面的樣本將 int 列(ytd_sales 列)轉換為 char(20) 列,以便使用 LIKE 子句。

USE pubs
GO
SELECT title, ytd_sales
FROM titles
WHERE CAST(ytd_sales AS char(20)) LIKE '15%'
   AND type = 'trad_cook'
GO


SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales
FROM titles
WHERE CONVERT(char(20), ytd_sales) LIKE '3%'


-----------------case和select語句結合(注意沒有逗號)------------------------------------------------------------
select 別名=case 列名   
when '值'   then '新值,哈哈'
when '值2'  then '我是值2'
else '我什麼都是不是'
end
from table


綜合例子:
SELECT Category = CASE type
    WHEN 'popular_comp' THEN 'Popular Computing'
    WHEN 'mod_cook' THEN 'Modern Cooking'
    WHEN 'business' THEN 'Business'
    WHEN 'psychology' THEN 'Psychology'
    WHEN 'trad_cook' THEN 'Traditional Cooking' ELSE 'Not yet categorized'    END,
CAST(title AS varchar(25)) AS 'Shortened Title',  
price AS Price
FROM titles
WHERE price IS NOT NULL
ORDER BY type, price
COMPUTE AVG(price) BY type




--B. 使用帶有簡單 CASE 函數和 CASE 搜尋函數的 SELECT 語句

USE pubs
GO
SELECT    'Price Category' =
      CASE
         WHEN price IS NULL THEN 'Not yet priced'
         WHEN price < 10 THEN 'Very Reasonable Title'
         WHEN price >= 10 and price < 20 THEN 'Coffee Table Title'
         ELSE 'Expensive book!'
      END,
   CAST(title AS varchar(20)) AS 'Shortened Title'
FROM titles
ORDER BY price
GO
--C. 使用帶有 SUBSTRING 和 SELECT 的 CASE 函數
USE pubs
SELECT SUBSTRING((RTRIM(a.au_fname) + ' '+
   RTRIM(a.au_lname) + ' '), 1, 25) AS Name, a.au_id, ta.title_id,
   Type =
  CASE
    WHEN SUBSTRING(ta.title_id, 1, 2) = 'BU' THEN 'Business'
    WHEN SUBSTRING(ta.title_id, 1, 2) = 'MC' THEN 'Modern Cooking'
    WHEN SUBSTRING(ta.title_id, 1, 2) = 'PC' THEN 'Popular Computing'
    WHEN SUBSTRING(ta.title_id, 1, 2) = 'PS' THEN 'Psychology'
    WHEN SUBSTRING(ta.title_id, 1, 2) = 'TC' THEN 'Traditional Cooking'
  END
FROM titleauthor ta JOIN authors a ON ta.au_id = a.au_id

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


---------goto語句---------------------------------
declare  @sum int, @count int
select   @sum=0, @count=1
label_1:
select  @sum=@sum+@count
select  @count=@count+1
if   @count<=5
goto  label_1
select  計數器的值=@count  ,和的值=@sum

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



-----------------某段預存程序欣賞-----------------------------------------------
Create Procedure update_title @title char(20),@title_id varchar(20)='tid111'
With encryption,recompile
as
Update titles set Title=@title  Where title_id=@title_id
-----------------------------------------------------------------




------------------某段觸發器欣賞-------------------------------------------------
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'employee_insupd' AND type = 'TR')
DROP TRIGGER employee_insupd
GO
CREATE TRIGGER employee_insupd ON employee FOR INSERT, UPDATE
AS
DECLARE @min_lvl tinyint,
@max_lvl tinyint,
@emp_lvl tinyint,
@job_id smallint
SELECT @min_lvl = min_lvl, @max_lvl = max_lvl, @emp_lvl = i.job_lvl, @job_id = i.job_id
FROM employee e INNER JOIN inserted i
ON e.emp_id = i.emp_id JOIN jobs j ON j.job_id = i.job_id

IF (@job_id = 1) and (@emp_lvl <> 10)
  BEGIN
  print 'Job id 1 expects the default  level of 10.'
  ROLLBACK TRANSACTION
END
ELSE
IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl)
BEGIN
print  'The level for job_id:'+cast(@job_id as varchar(5))+' should be between   '+cast(@min_lvl as varchar(5))+'  and '+cast(@max_lvl as varchar(5))
ROLLBACK TRANSACTION
END
/*/////////////////////////////////////////////////////////*/
--(c)在視圖CustomersView上建立一個INSTEAD OF觸發器:
CREATE TRIGGER Customers_Update2  ON CustomersView
  INSTEAD OF UPDATE
AS
   DECLARE @Country nvarchar(15)
  SET @Country = (SELECT Country FROM Inserted)
IF @Country = 'Germany'
   BEGIN
    UPDATE CustomersGer
         SET CustomersGer.Phone = Inserted.Phone
         FROM CustomersGer JOIN Inserted
         ON CustomersGer.CustomerID = Inserted.CustomerID
   END
ELSE
IF @Country = 'Mexico'
   BEGIN
      UPDATE CustomersMex
      SET CustomersMex.Phone = Inserted.Phone
      FROM CustomersMex JOIN Inserted
       ON CustomersMex.CustomerID = Inserted.CustomerID
END
-------------------------------------------------------------------


create trigger 觸發器名 on 視圖名
INSTEAD OF insert as print '視圖執行了insert操張'
--在視圖上建立觸發器,用instead of

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

sp_helptrigger abc  --查看觸發器abc的相關資訊

-------------------------------------------------------------------------
執行預存程序的二種方式:
exec GetOrderDetails2
@enddate='1998-5-30',
@startdate='1997-7-1',
@country='USA'
--或:
exec GetOrderDetails2
'1997-7-1','1998-5-30','USA'
----------------------------------------------------------------------------

**************遊標cursor**********************************************

SQL Server支援四種伺服器資料指標類型:
(a) static       基本上不監測變化
(b) dynamic  可監測變化
(c) forward 只可以取後面的資料
(d) keyset 介於static 和 dynamic之間

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

DECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR
FOR select_statement
[ FOR { READ ONLY | UPDATE [ OF column_name [ ,...n ] ] } ]

----------------------------------------------------------------------------
DECLARE cursor_name CURSOR
[ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ]
FOR select_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ]

----------定義遊標的一個執行個體------------------------------------------------------------------
DECLARE Employee_Cursor
CURSOR FOR       -----SQL語句
SELECT au_lname, au_fname, phone
FROM authors
WHERE au_lname LIKE 'Ring%'
OPEN Employee_Cursor ---開啟遊標
FETCH NEXT FROM Employee_Cursor
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM Employee_Cursor
END
CLOSE Employee_Cursor
DEALLOCATE Employee_Cursor

--------------------------------------------------------------------
FETCH?[[NEXT|PRIOR|FIRST|LAST|ABSOLUTE{n|@nvar }?| RELATIVE { n | @nvar }]?FROM]{ { [ GLOBAL ] cursor_name } | @cursor_variable_name } [ INTO @variable_name [ ,...n ] ]
從 Transact-SQL 伺服器資料指標中檢索特定的一行

--------------------------------------------------------------------------
declare aa cursor scroll for select * from cursorabc  --定義一個可以上下移動的scroll遊標
open aa --開啟遊標


while @@fetch_status=0  --用while循行把所有記錄集讀取出來
fetch next from aa


fetch absolute 5 from aa --定位到記錄集第五行
fetch next from aa   --定位到下一行
fetch prior from aa  --定位到上一行
fetch first from aa  --定位到第一行
fetch last from aa   --定位到最後一行
fetch relative -4 from aa  --相對後退四條記錄




if @@FETCH_STATUS =0
print '返回0,說明讀取記錄正常,並沒有到最後一條或第一條記錄'
else
print '不是返回0,說明指標到了最後或在最開始,或沒有記錄集'

print '該記錄集的總行數為:'+cast(@@cursor_rows as varchar(5))  --該記錄集的總行數


close aa
deallocate aa

----------------------------------------------------------------------------------------------
DECLARE @price money
DECLARE @get_price CURSOR
SET @get_price = CURSOR FOR  SELECT price FROM titles
OPEN @get_price
FETCH NEXT FROM @get_price INTO @price
SELECT price FROM titles
WHILE (@@FETCH_STATUS = 0)
BEGIN
IF @Price < 20
  UPDATE titles SET price =
   (@price + (@price * .1))
  WHERE CURRENT OF @get_price
ELSE
  UPDATE titles SET price =
   (@price + (@price * .05))
  WHERE CURRENT OF @get_price
FETCH NEXT FROM @get_price INTO @price
END
SELECT price FROM titles
CLOSE @get_price
DEALLOCATE @get_price
-------------------------------------------------------------------------------------------------
SET NOCOUNT ON
DECLARE @au_id varchar(11),
                    @au_fname varchar(20),  
                    @au_lname varchar(40),
                    @message varchar(80),
                    @title varchar(80)
PRINT '---California Authors report ---'
DECLARE authors_cursor CURSOR FOR
SELECT au_id, au_fname, au_lname FROM authors
WHERE state = 'CA' ORDER BY au_id

OPEN authors_cursor
FETCH NEXT FROM authors_cursor INTO @au_id, @au_fname, @au_lname
WHILE @@FETCH_STATUS = 0
BEGIN
   PRINT ''
   SELECT @message = '----- Books by Author: ' + @au_fname + ' ' + @au_lname
   PRINT @message
-- Declare an inner cursor based
-- on au_id from the outer cursor.
DECLARE titles_cursor CURSOR FOR SELECT t.title FROM titleauthor ta, titles t
WHERE ta.title_id = t.title_id AND ta.au_id = @au_id
-- Variable value from the outer cursor
OPEN titles_cursor
FETCH NEXT FROM titles_cursor INTO @title
IF @@FETCH_STATUS <> 0
     PRINT 'No Books'
WHILE @@FETCH_STATUS = 0
BEGIN
       SELECT @message ='' + @title      
       PRINT @message
       FETCH NEXT FROM titles_cursor INTO @title
END
CLOSE titles_cursor  
DEALLOCATE titles_cursor
-- Get the next author.
FETCH NEXT FROM authors_cursor INTO @au_id, @au_fname, @au_lname
END
CLOSE authors_cursor
DEALLOCATE authors_cursor
GO
------------------------------------------------------------------------------------------------

--------------藉助暫存資料表實現和用遊標同樣的效果--------------------------------------------------------
--定義暫存資料表時,只要在表名前加#井字元即可,如:select * into #temptable from tablename

use pubs
go
select * into titles2 from titles
select * into #temp1 from titles2 where price<20
select * into #temp2 from titles2 where price>=20
go
UPDATE #temp1 SET price = price+(price*0.1) WHERE price < 20
UPDATE #temp2 SET price = price +(price * 0.05) WHERE price >= 20
go
delete from titles2
insert into titles2 select * from #temp1
insert into titles2 select * from #temp2
go
select * from titles
go
select * from titles2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.