วันอังคารที่ 19 กรกฎาคม พ.ศ. 2554

SQL

ตัวอย่างคำสั่ง SQL
use myserverdb
select * from categories
select *
from categories
order by categoryid desc
select *
from categories
where categoryid = 1
or categoryid =3
or categoryid =5
or categoryid =7
select *
from categories
where categoryid % 2 = 1
select *
from categories
where categoryid % 2 <> 1
insert into categories(categoryid,
categoryname) values(9,'Test')
-- เพิ่มรายการใหม่ลงในตาราง categories
-- ผลลัพธ์ที่ได้คือ (1 row(s) afftected)
-- ต้องการทราบว่าได้รายการเพิ่มต้องเรียกดู
-- ด้วยคำสั่ง select เอง
select *
from categories
insert into categories(categoryid,
categoryname) values(10,'ทดสอบ')
-- update
update categories
set categoryname='Test All'
-- แก้ไขตาราง categories โดยการกำหนดค่าของ
-- categoryname ให้มีค่า ='Test All'
-- ข้อควรระวัง
-- คำสั่งนี้มีผลกับทุก record ในตาราง  categories
update categories
set categoryname='Test All'
where categoryname='Test '
select *
from categories
order by categoryid
delete from categories
-- ข้อควรระวัง
-- คำสั่งนี้มีผลกับทุก record ในตาราง  categories
delete from categories
where categoryid = 1
select *
from categories
where categoryid between 2 and 5
select *
from categories
where categoryid >= 2 and categoryid <= 5
--2,3,4,8,9
select *
from categories
where categoryid in(2,3,4,8,9)
order by categoryid
select *
from categories
where categoryname = 'Seafood'
select *
from categories
where categoryname like 'c%'
-- c% ขึ้นต้นด้วย c
select *
from categories
where categoryname like '%c'
-- %c ลงท้ายด้วย c
-- มี c เป็นส่วนประกอบ
select *
from categories
where categoryname like '%c%'
select count(*)
from  categories
-- ในตาราง categories มีกี่ record

select count(*) as 'จำนวนรายการในตาราง'
from  categories
select count(categoryid) as 'จำนวนรายการในตาราง'
from  categories
select max(categoryid) as 'MaxID'
from  categories
select min(categoryid) as 'MinID'
from  categories
select avg(categoryid) as 'AvgID'
from  categories
select max(categoryid) as 'MaxID',
min(categoryid) as 'MinID',
avg(categoryid) as 'AvgID'
from  categories

select sum(categoryid) as 'SumOfID'
from  categories
select *
from view_1
select *
from view_1
order by categoryid
create view MyView
as
select sum(categoryid) as 'SumOfID'
from  categories
select *
from MyView
select country
from customers
order by country
select distinct country
from customers
order by country
-- distinct หมายถึงแตกต่าง
-- คือข้อมูลที่ซ้ำกันให้แสดงเพียงรายการเดียว
=========================

ไม่มีความคิดเห็น:

แสดงความคิดเห็น