數據庫經常使用sql語句

 

=======對錶結構的訪問與操做============

 

1、獲取數據庫下全部的表名

select name from NewWorkLog.sys.tables go --NewWorkLog爲表名

 

2、要是隻獲取特定表裏特定的字段的數據類型

SELECT data_type  FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME ='hos_booking' and COLUMN_NAME='bk_sn' --hos_booking爲表名,bk_sn 爲字段名

3、獲取表結構詳細信息

SELECT 
    表名       = case when a.colorder=1 then d.name else '' end,
   
    字段序號   = a.colorder,
    字段名     = a.name,
    標識       = case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end,
    主鍵       = case when exists(SELECT 1 FROM sysobjects where xtype='PK' and parent_obj=a.id and name in (
                     SELECT name FROM sysindexes WHERE indid in(
                        SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid))) then '√' else '' end,
    類型       = b.name,
    佔用字節數 = a.length,
    長度       = COLUMNPROPERTY(a.id,a.name,'PRECISION'),
    小數位數   = isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
    容許空     = case when a.isnullable=1 then '√'else '' end,
    默認值     = isnull(e.text,'')
 
FROM 
    syscolumns a
left join 
    systypes b 
on 
    a.xusertype=b.xusertype
inner join 
    sysobjects d 
on 
    a.id=d.id  and d.xtype='U' and  d.name<>'dtproperties'
left join 
    syscomments e 
on 
    a.cdefault=e.id
where 
    d.name='Department'    --若是隻查詢指定表,加上此條件
order by 
    a.id,a.colorder

4、獲取表結構詳細信息,包括說明。上面的並無附加說明

  SELECT
                                     [列名]=a.name,
                                     [數據類型]=b.name,
                                     [長度]=COLUMNPROPERTY(a.id,a.name,'PRECISION'),
                                     [是否爲空]=case when a.isnullable=1 then '√'else '' end,
                                     [默認值]=isnull(e.text,''),
                                     [說明]=isnull(g.[value],'未填說明')
                                     FROM syscolumns a
                                     left join systypes b on a.xusertype=b.xusertype
                                     inner join sysobjects d on a.id=d.id  and d.xtype='U' and  d.name<>'dtproperties'
                                     left join syscomments e on a.cdefault=e.id
                                     left join sys.extended_properties g on a.id=g.major_id and a.colid=g.minor_id 
                                     left join sys.extended_properties f on d.id=f.major_id and f.minor_id=0where d.name='Base_Organization' order by a.id,a.colorder
                                     --Base_Organization是咱們要獲取表結構的表名

5、修改字段默認值

格式:正則表達式

alter table 表名 drop constraint 約束名字
說明:刪除表的字段的原有約束
alter table 表名 add constraint 約束名字 DEFAULT 默認值 for 字段名稱
--經過sysdatetime()函數獲取當前的默認時間
alter table dbo.Orders
add constraint dft_Orders_orderts
default(sysdatetime()) for orderts

 

--實例
USE [RM_DB]
GO
alter table [dbo].[Base_Dic_Organize] drop constraint DF__EAI_DIC_O__del_f__14270015
ALTER TABLE [dbo].[Base_Dic_Organize] ADD  DEFAULT ('1') FOR [DeleteMark]
GO
--[RM_DB] 爲數據庫
--[Base_Dic_Organize] 爲須要對其約束的字段所在的表名
--DF__EAI_DIC_O__del_f__14270015 爲已經存在的約束名
--[DeleteMark]  須要約束的字段

六.約束

     1.惟一性約束sql

--若是想同時約束多列惟一性,能夠在Name後面指定多個,且以逗號相隔便可
alter table Dict_rgt_Unit add constraint uniqueUnitName unique(Name)

    2.主鍵約束數據庫

--給表添加主鍵
use [TSQL2012]
if OBJECT_ID('dbo.Employees','U') is not null  
 begin 
alter table dbo.Employees
add constraint PK_Employees primary key ([empid]) 
end

  3.Check約束express

use [TSQL2012]
if object_id ('dbo.Employees','U') IS NOT NULL
begin
alter table dbo.Employees
add constraint Ck_salary check([salary]>0)
end

4.外鍵約束編程

--與其餘表創建外鍵約束,orders中的empid的值只能來自emplyees表中的empid
alter table dbo.orders
add constraint FK_orders_Employees foreign key (empid)
references dbo.employees(empid);
--單張表對自身設置外鍵。mgrid的值只能來自同表的empid
alter table dbo.Employees
add constraint FK_Employees_Employees  foreign key ([mgrid])
references dbo.Employees(empid);

 

七.建立表

--OBJECT_ID是內置函數,查詢表dbo.Empleyees是否是在數據庫中。U表示爲用戶表
--建立一張新表建議顯示置頂是否爲空。
if OBJECT_ID('dbo.Employees','U') is not null  
   drop table dbo.Employees
   create table dbo.Employees
   (
   empid int not null,
   firstname varchar(30) not null,
   lastname varchar(30) not null,
   hiredate date not null,
   mgrid int null,
   ssn varchar(20) not null,
   salary money not null
   );

==========對錶數據的操做==============

1、查詢部分

  1. 單表查詢

    select  *  from  [表名】  where   條件

  2. offset -fetch 篩選(默認最好使用這個,而不是用top,前者是標準的,top不是。)
  3. --排序後,跳過五十行後,截取後面的25行數據
    select orderid,orderdate,custid,empid 
    from Sales.Orders
    order by orderdate,orderid
    offset 50 rows fetch next 25  rows only;
    --排序後,跳過0行後,截取後面的2行數據
    select orderid,orderdate,custid,empid 
    from Sales.Orders
    order by orderdate,orderid
    offset 0 rows fetch next 2  rows only;
    --排序後,跳過五行後,獲取後面全部的數據
    select orderid,orderdate,custid,empid 
    from Sales.Orders
    order by orderdate,orderid
    offset 5 rows ;

    3.條件謂詞函數

    --條件謂詞between ... and ...
    select orderid ,empid,orderdate
    from Sales.Orders
    where orderid between 10300 and 10310;
    
    --條件謂詞in
    select orderid,empid,orderdate
    from Sales.Orders
    where orderid in (10248,10249,10250);
    
    --條件謂詞LIKE(裏面的N表明着數據類型爲nvarchar或者nchar)
    select empid,firstname,lastname
    from HR.Employees 
    where lastname like N'D%';

    ps:條件謂詞=,>,<,>=,<=,<>是標準的謂詞,!>,!<,!=是標準的。咱們應該儘可能使用標準化的語法格式.fetch

  4. 算術運算符在查詢中的運用優化

    select 
    orderid,
    productid,
    qty,
    unitprice,
    discount,
    qty*unitprice*(1-discount) as val
    from Sales.OrderDetails;

     

  5. case 表達式spa

    use [TSQL2012]
    --通常用法
    select productid,productname,categoryid,
    case categoryid
    when 1 then 'Beverages'
    when 2 then 'x'
    when 3 then 'y'
    when 4 then 'i'
    else 'hh'
    end as categoryname
    from Production.Products;
    
    --加入計算邏輯的case語句
    select 
    orderid,
    custid,
    val,
    case 
    when val<1000.00 then '少於1000'
    when val between 1000.00 and 3000.00 then '1000到3000之間'
    when val >3000.00 then '超過3000'
    else  '未知'
    end as valuecategory
    from Sales.OrderValues;
    
    --case在條件查詢中的運用
    select col1,col2
    from dbo.T1
    where 
    case 
    when col1=0 then 'no'
    when col2/col1>2 then 'yes'
    else 'no'
    end ='yes'

     

  6. 多表聯查

    I.left  join(左連接)code

    select  a.*   from   [表1]  as  a   left   join  [表2】 as b

    on   a.字段名=b.字段名  

    where  條件

  7. group by子句,實現分組查詢

  8. 區分大小寫的查詢

    --數據庫默認不區分大小寫查詢,查詢結果集有兩個,rabbit,和Rabbit
    select name from dbo.userCenter
    where name='rabbit';
    
    --區分大小寫的查詢,只查詢出一個數據,rabbit。Rabbit被過濾掉了
    select name from dbo.userCenter
    where name  collate latin1_General_CS_AS=N'rabbit';

     

================經常使用系統函數=======================

1.row_number()計算行號的。須要和over子句搭配,over子句需和order by子句搭配。主要能夠對某個字段培訓後,分組計算行號。示例sql,示例效果以下

sql示例:

select
 orderid,
 custid,
 val,
 ROW_NUMBER() over (partition by custid order by val) as rownum
from  Sales.OrderValues

效果以下:

 

 

2.cast函數,強制轉換輸出的數據類型

示例以下

--使用cast函數將單價數據轉爲整型
select 
orderid,
productid,
qty,
cast( unitprice as int) as price,
discount,
qty*unitprice*(1-discount) as val
from Sales.OrderDetails;

3.coalesce支持兩個或多個參數,isnull函數只支持兩個參數,且前者仍是標準的。建議使用前者

--coalesce(orderid,custid)返回多個參數中第一個非null的值。orderid若爲null,則返回custid的值。若不爲null,則返回orderid的值
use [TSQL2012]
select orderid,custid,coalesce(orderid,custid) 
from Sales.OrderValues;

4.IIF(<logical_expression>,<expr1>,<expr2>),

   功能描述:若是logical_expression爲true時,返回expr1,不然返回expr2.

   示例

--IIF(<logical_expression>,<expr1>,<expr2>)
use [TSQL2012]
select orderid,custid,IIF(orderid<10249,custid,orderid) 
from Sales.OrderValues;

*SUBSTRING(string,start,length)

功能描述:用於對輸入的字符串string,從start位置開始,提取length個字符。(注意起始位置是1不是0)

實例:

--substring 函數用法示例
select  SUBSTRING('abcde',1,2) as 子串;

 *LEFT(string,n) 和RIGHT(string,n)

功能描述:left函數做用是對輸入的字符串string,提取坐起n個長度的子串。right函數的做用是對輸入的字符串string,提取右起的n個長度的子串

示例:

--LEFT函數示例
select LEFT('abcdef',2);

--RIGHT函數示例
select RIGHT('abckdfasd',3);

*CHARINDEX(substring,string[,start_pos])

返回子字符串(substring)在字符串(string)的第一次出現的位置。第三個參數若是被指定,則從字符串的指定起始位置開始匹配。若是不指定,則默認從0開始匹配。未找到則返回0.

--返回6
select CHARINDEX(' ','Itzik Ben-Gan')
--返回3
select CHARINDEX('bb','rabbit');
--返回3,不區分大小寫
select CHARINDEX('B','rabbit');
--返回0
select CHARINDEX('d','rabbit');

*PATINDEX(pattern,string)

描述:返回模式在字符串中第一次出現的位置

--有點相似正則表達式。返回5
select PATINDEX('%[0-9]%','abcd123efgh');

*REPLACE(string,substring1,substring2)

描述:使用sub2替換string字符串中出現的全部sub1

--返回ab:cd:de
select replace ('ab-cd-de','-',':');

*REPLICATE(string,n)

描述:string字符串按照指定的次數n重複鏈接後返回

--返回RabbitRabbit
select REPLICATE('Rabbit',2);

*RTRM和LTRM

描述:分別表示返回刪除尾隨或者前面空格後的輸入字符串

--去掉字符串右邊尾部的空格
select RTRIM('    dfsd df    ')
--去掉字符串左邊尾部的空格
select LTRIM('       ddd   ');

*LIKE謂詞

經過通配符,對字符串進行模式匹配

示例:

--%通配符,百分號表明任意大小的字符串,包括空字符。like比substring優化
--如下示例,展現名字以D開頭的員工
select empid,lastname
from HR.Employees
where lastname like N'D%'

--_(下劃線) 通配符

--相似佔位的意思,好比下面,則返回第二個字符是‘e‘的員工
select empid, lastname

from HR.Employees
where lastname like N'_e%';

--[<List of characters>]通配符
--方括號內帶有的字符列表,表明單個字符必須是列表中指定的字符之一。
--下面的查詢返回姓氏第一個帶有A,或B,或C的員工
select empid,lastname
from HR.Employees
where lastname like N'[ABC]%'

--[^<character list or range>] 通配符
--方括號內又有插入符號,後跟一個字符列表或者字符範圍(如[^A-E]),表明單個字符
--未在指定的字符列表或範圍內。
--示例:姓氏的第一個字符不是字母A~E範圍的僱員

select empid,lastname
from HR.Employees
where lastname like N'[A-E]%'

--對字符串包含有統配符進行搜索用[]括起來
select  empid,lastname
from hr.Employees
where lastname like N'_[%]%';

====================常見誤區====================================

1.sql的同時操做,where條件的判斷能夠按任意順序,sql根據成本估計來決定先運算那個邏輯條件。這一點是不一樣於編程的。

--常見誤區,先判斷col1不等於0,在判斷相除的值大於2。
--可是sql的where條件是同時操做的,執行的順序是任意的。會根據成本估計。
--而不是一成不變的從左到有的判斷。一旦先判斷col2/col1的值就會報錯了
select col1,col2
from dbo.T1
where  col1<> 0 and col2/col1 >2;

--正確作法
select col1,col2
from dbo.T1
where 
case 
when col1=0 then 'no'
when col2/col1>2 then 'yes'
else 'no'
end ='yes';

                                                                                                                                                                =========================注意的小細節============================

* +號鏈接符連接字符串的時候,若是鏈接的是null,則整個結果就是null。

可是concat函數則不會,它會將null替換成空字符。

--使用+運算符鏈接字符串,若是鏈接時的NULL,則結果會爲NULL
select 
custid,country,region,city,
country+N''+region+N''+city as location
from Sales.Customers

--使用concat函數鏈接,若是碰到null,會將null替換成空字符. 可是注意concat函數只在sql server2012及其以上纔有的.
select 
custid,country,region,city,
concat(country,N','+region,N','+city) as loaction
from Sales.Customers


--若是有些版本過低,不能使用concat,能夠用coalesce函數和+運算符混合使用達到要求
select 
custid,country,region,city,
coalesce(country,'無')+N','+coalesce(region,N'無')+N','+coalesce(city,N'無')
from Sales.Customers
相關文章
相關標籤/搜索