Sql Server是鄙人學習的第一種數據庫,對Sql Server有一種特別的情感,下面就說一下Sql Server的簡單語法,適用初學者。
1,創建數據庫 create database
create
database
My_FrirstCreate
--
創建數據庫
go
use
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
)
go
insert
dbo.Students
values
(
100204202
,
'
李四
'
,
null
)
go
insert
into
table1
--
利用insert,select向表里插數據
select
ID,Name,Date
from
table2
where
Name
=
"張三";
go
? 4,使用select,into創建新表
select
{列名}
--
使用select,into創建新表
into
新表名
from
舊表;
5,更新,刪除數據 update? delete
update
dbo.Students
--
更新數據
set
Scores
=
70
where
StudentID
=
100204202
go
delete
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.ModelName
from
dbo.DimProduct t
where
t.ModelName
like
'
hl%
'
;
--
檢索名稱以‘hl’結尾的信息
select
t.ProductKey,t.ModelName
from
dbo.DimProduct t
where
t.ModelName
like
'
%hl
'
;
--
檢索名稱類似‘hl’的信息
select
t.ProductKey,t.ModelName
from
dbo.DimProduct t
where
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.DimProduct
group
by
Color;
--
商品庫中:相同顏色產品數量大于50的商品顏色
select
color,
COUNT
(
*
)
from
dbo.DimProduct
group
by
Color
having
count
(
*
)
>=
50
;
select
*
from
dbo.DimProduct
order
by
Color
asc
;
select
color,
COUNT
(
*
)
from
dbo.DimProduct
group
by
Color
having
count
(
*
)
>=
50
order
by
COUNT
(
*
)
asc
;
select
color,
COUNT
(
*
)
from
dbo.DimProduct
group
by
Color
having
count
(
*
)
>=
50
order
by
COUNT
(
*
)
desc
;
--
商品庫中:1998生產的,相同顏色產品數量大于5的商品顏色
select
color,
COUNT
(
*
)
from
dbo.DimProduct
where
YEAR
(StartDate)
=
1998
group
by
Color
having
count
(
*
)
>=
50
order
by
COUNT
(
*
)
desc
;
select
color,
count
(
*
)
from
dbo.DimProduct t
where
YEAR
(t.StartDate)
>
1998
group
by
color
having
COUNT
(
*
)
>
50
order
by
COUNT
(
*
)
desc
;
? 10,聯接join語法
select
m.LoginID
as
ManagerLoginID,e.
*
--
左聯接
from
HumanResources.Employee e
left
join
HumanResources.Employee m
on
m.employeeID
=
e.ManagerID
select
m.LoginID
as
ManagerLoginID,e.
*
--
右聯接
from
HumanResources.Employee e
right
join
HumanResources.Employee m
on
m.employeeID
=
e.ManagerID
?
? 本文只是簡單的介紹下T-Sql語法,復雜的語法將下面的文章講解...
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
