Sql Server是鄙人學習的第一種資料庫,對Sql Server有一種特別的情感,下面就說一下Sql Server的簡單文法,適用初學者。
1,建立資料庫create database
create database My_FrirstCreate --建立資料庫gouse My_FrirstCreate --串連資料庫 go
2,建立表create table
create table dbo.Students --建立表(資料類型,是否NULL) (StudentID int primary key not null, Name varchar(25)not null, Scores int null)go
3,插入資料insert
insert dbo.Students(StudentID,Name,Scores) --插入資料 values(100204201,'張三',50)goinsert dbo.Students values(100204202,'李四',null)goinsert into table1 --利用insert,select向表裡插資料 select ID,Name,Date from table2where Name="張三";go
4,使用select,into建立新表
select{列名} --使用select,into建立新表into 新表名from 舊錶;
5,更新,刪除資料update delete
update dbo.Students --更新資料 set Scores=70 where StudentID=100204202godelete from Students where Name='張三'
6,改變欄位的屬性
alter table Produce.Product --改變欄位的屬性alter column Name char(50) not null
7,資料類型轉換
print cast ('2011-12-12' as datetime) --cast類型轉換print convert(datetime,getdate()) --convert類型轉換
8,like查詢文法
--檢索名稱以‘hl’開頭的資訊select t.ProductKey,t.ModelNamefrom dbo.DimProduct twhere t.ModelName like 'hl%';--檢索名稱以‘hl’結尾的資訊select t.ProductKey,t.ModelNamefrom dbo.DimProduct twhere t.ModelName like '%hl';--檢索名稱類似‘hl’的資訊select t.ProductKey,t.ModelNamefrom dbo.DimProduct twhere t.ModelName like '%hl%';
9,條件查詢文法
--每種顏色有多種件產品:select COUNT(*) from dbo.DimProduct;select * from dbo.DimProduct where Color = 'black';select count(*) from dbo.DimProduct where Color = 'black';--分組:select color from dbo.DimProduct;select color,COUNT(*) from dbo.DimProductgroup by Color;--商品庫中:相同顏色產品數量大於50的商品顏色select color,COUNT(*) from dbo.DimProductgroup by Colorhaving count(*) >= 50;select * from dbo.DimProductorder by Color asc;select color,COUNT(*) from dbo.DimProductgroup by Colorhaving count(*) >= 50order by COUNT(*) asc;select color,COUNT(*) from dbo.DimProductgroup by Colorhaving count(*) >= 50order by COUNT(*) desc;--商品庫中:1998生產的,相同顏色產品數量大於5的商品顏色select color,COUNT(*) from dbo.DimProductwhere YEAR(StartDate)=1998group by Colorhaving count(*) >= 50order by COUNT(*) desc;select color,count(*) from dbo.DimProduct twhere YEAR(t.StartDate)>1998group by colorhaving COUNT(*)>50order by COUNT(*) desc;
10,聯結join文法
select m.LoginID as ManagerLoginID,e.* --左聯結from HumanResources.Employee eleft join HumanResources.Employee mon m.employeeID = e.ManagerIDselect m.LoginID as ManagerLoginID,e.* --右聯結from HumanResources.Employee eright join HumanResources.Employee mon m.employeeID = e.ManagerID
本文只是簡單的介紹下T-Sql文法,複雜的文法將下面的文章講解...