天天看點

sql語句大全

  建立之前判斷該資料庫是否存在

  if exists (select * from sysdatabases where name='databaseName')

  drop database databaseName

  go

  Create DATABASE database-name

  drop database dbname

  --- 建立備份資料的 device

  USE master

  EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'

  --- 開始備份

  BACKUP DATABASE pubs TO testBack

  create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)

  根據已有的表建立新表:

  A:go

  use 原資料庫名

  select * into 目的資料庫名.dbo.目的表名 from 原表名(使用舊表建立新表)

  B:create table tab_new as select col1,col2… from tab_old definition only

  create sequence SIMON_SEQUENCE

  minvalue 1 -- 最小值

  maxvalue 999999999999999999999999999 -- 最大值

  start with 1 -- 開始值

  increment by 1 -- 每次加幾

  cache 20;

  drop table tabname

  Alter table tabname add column col type

  Alter table tabname drop column colname

  Alter table tabname add primary key(col)

  說明:删除主鍵:Alter table tabname drop primary key(col)

  create [unique] index idxname on tabname(col…。)

  删除索引:drop index idxname on tabname

  注:索引是不可更改的,想更改必須删除重建立。

  create view viewname as select statement

  删除視圖:drop view viewname

  (1) 資料記錄篩選:

  sql="select * from 資料表 where 字段名=字段值 order by 字段名 [desc]"

  sql="select * from 資料表 where 字段名 like '%字段值%' order by 字段名 [desc]"

  sql="select top 10 * from 資料表 where 字段名 order by 字段名 [desc]"

  sql="select * from 資料表 where 字段名 in ('值1','值2','值3')"

  sql="select * from 資料表 where 字段名 between 值1 and 值2"

  (2) 更新資料記錄:

  sql="update 資料表 set 字段名=字段值 where 條件表達式"

  sql="update 資料表 set 字段1=值1,字段2=值2 …… 字段n=值n where 條件表達式"

  (3) 删除資料記錄:

  sql="delete from 資料表 where 條件表達式"

  sql="delete from 資料表" (将資料表所有記錄删除)

  (4) 添加資料記錄:

  sql="insert into 資料表 (字段1,字段2,字段3 …) values (值1,值2,值3 …)"

  sql="insert into 目标資料表 select * from 源資料表" (把源資料表的記錄添加到目标資料表)

  (5) 資料記錄統計函數:

  AVG(字段名) 得出一個表格欄平均值

  COUNT(*¦字段名) 對資料行數的統計或對某一欄有值的資料行數統計

  MAX(字段名) 取得一個表格欄最大的值

  MIN(字段名) 取得一個表格欄最小的值

  SUM(字段名) 把資料欄的值相加

  引用以上函數的方法:

  sql="select sum(字段名) as 别名 from 資料表 where 條件表達式"

  set rs=conn.excute(sql)

  用 rs("别名") 擷取統計的值,其它函數運用同上。

  查詢去除重複值:select distinct * from table1

  (5) 資料表的建立和删除:

  CREATE TABLE 資料表名稱(字段1 類型1(長度),字段2 類型2(長度) …… )

  A:UNION 運算符

  UNION 運算符通過組合其他兩個結果表(例如TABLE1 和TABLE2)并消去表中任何重複行而派生出一個結果表。當 ALL 随UNION 一起使用時(即UNION ALL),不消除重複行。兩種情況下,派生表的每一行不是來自TABLE1 就是來自TABLE2。

  B: EXCEPT 運算符

  EXCEPT 運算符通過包括所有在TABLE1 中但不在TABLE2 中的行并消除所有重複行而派生出一個結果表。當ALL 随EXCEPT 一起使用時(EXCEPT ALL),不消除重複行。

  C:INTERSECT 運算符

  INTERSECT 運算符通過隻包括TABLE1 和TABLE2 中都有的行并消除所有重複行而派生出一個結果表。當ALL 随INTERSECT 一起使用時(INTERSECT ALL),不消除重複行。

  注:使用運算詞的幾個查詢結果行必須是一緻的。

  A、left outer join:

  SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

  B:right outer join:

  右外連接配接(右連接配接):結果集既包括連接配接表的比對連接配接行,也包括右連接配接表的所有行。

  C:full outer join:

  全外連接配接:不僅包括符号連接配接表的比對行,還包括兩個連接配接表中的所有記錄。

  if exists (select * from sys.databases where name = '資料庫名')

  drop database [資料庫名]

  if not exists (select * from sysobjects where [name] = '表名' and xtype='U')

  begin

  --這裡建立表

  end

  if exists (select * from sysobjects where id = object_id(N'[存儲過程名]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

  drop procedure [存儲過程名]

  if object_id('tempdb..#臨時表名') is not null

  drop table #臨時表名

  --SQL Server 2000

  IF EXISTS (SELECT * FROM sysviews WHERE object_id = '[dbo].[視圖名]'

  --SQL Server 2005

  IF EXISTS (SELECT * FROM sys.views WHERE object_id = '[dbo].[視圖名]'

  if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[函數名]') and xtype in (N'FN', N'IF', N'TF'))

  drop function [dbo].[函數名]

  SELECT [name],[id],crdate FROM sysobjects where xtype='U'

  /*

  if exists(select * from syscolumns where id=object_id('表名') and name='列名')

  alter table 表名drop column 列名

  if columnproperty(object_id('table'),'col','IsIdentity')=1

  print '自增列'

  else

  print '不是自增列'

  SELECT * FROM sys.columns WHERE object_id=OBJECT_ID('表名')

  AND is_identity=1

  if exists(select * from sysindexes where id=object_id('表名') and name='索引名')

  print '存在'

  print '不存在

  SELECT * FROM sys.sysobjects WHERE name='對象名'

  select * from table(所要查詢的表名) where coloum(條件)

  (隻複制結構,源表名:a 新表名:b) (Access可用)

  法一:select * into b from a where 1<>1

  法二:select top 0 * into b from a

  (拷貝資料,源表名:a 目标表名:b) (Access可用)

  insert into b(x, y, z) select d,e,f from a;

  (具體資料使用絕對路徑) (Access可用)

  insert into b(x, y, z) select d,e,f from a in ‘具體資料庫’ where 條件

  例子:。.from b in '"&Server.MapPath("."&"\data.mdb" &"' where..

  (表名1:a 表名2:b)

  select a,b,c from a where a IN (select d from b 或者: select a,b,c from a where a IN (1,2,3)

  select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b

  select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

  (表名1:a

  select * from (Select a,b,c FROM a) T where t.a > 1;

  between限制查詢資料範圍時包括了邊界值,not between不包括

  select * from table1 where time between time1 and time2

  select a,b,c, from table1 where a not between 數值1 and 數值2

  select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)

  兩張關聯表delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1

  select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....

  SQL: select * from 日程安排 where datediff('minute',f開始時間,getdate())>5

  select top 10 b.* from (select top 20 主鍵字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主鍵字段= a.主鍵字段 order by a.排序字段

  select top 10 * from table1 where 範圍

  選擇在每一組b值相同的資料中對應的a最大的記錄的所有資訊(類似這樣的用法可以用于論壇每月排行榜,每月熱銷産品分析,按科目成績排名,等等。)

  select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)

  包括所有在TableA 中但不在TableB和TableC 中的行并消除所有重複行而派生出一個結果表

  (select a from tableA except (select a from tableB) except (select a from tableC)

  select top 10 * from tablename order by newid()

  select newid()

  Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)

  select name from sysobjects where type='U'

  select name from syscolumns where id=object_id('TableName')

  列示type、vender、pcs字段,以type字段排列,case可以友善地實作多重選擇,類似select 中的case。

  select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type

  顯示結果:

  type vender pcs

  電腦A 1

  CD光牒A 2

  手機B 3

  手機C 3

  TRUNCATE TABLE table1

  select top 5 * from (select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc) table_2 order by id

  declare @numid int

  declare @id varchar(50)

  set @numid=2005

  set @id=convert(varchar,@numid)

  通過上述語句完成資料類型Int轉換成varchar,其他轉換類似,可參看convert函數

技巧

  在SQL語句組合時用的較多

  “where 1=1”是表示選擇全部 “where 1=2”全部不選,

  如:

  if @strWhere !='

  set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere

  set @strSQL = 'select count(*) as Total from [' + @tblName + ']'

  我們可以直接寫成

  set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 and '+ @strWhere

  --重建索引

  DBCC REINDEX

  DBCC INDEXDEFRAG

  --收縮資料和日志

  DBCC SHRINKDB

  DBCC SHRINKFILE

  dbcc shrinkdatabase(dbname)

  轉移資料庫給新使用者以已存在使用者權限

  exec sp_change_users_login 'update_one','newname','oldname'

  RESTORE VERIFYONLY from disk='E:\dvbbs.bak'

  Alter DATABASE [dvbbs] SET SINGLE_USER

  GO

  DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK

  Alter DATABASE [dvbbs] SET MULTI_USER

  SET NOCOUNT ON

  DECLARE @LogicalFileName sysname,

  @MaxMinutes INT,

  @NewSize INT

  USE tablename -- 要操作的資料庫名

  @MaxMinutes = 10, -- Limit on time allowed to wrap log.

  @NewSize = 1 -- 你想設定的日志檔案的大小(M)

  -- Setup / initialize

  DECLARE @OriginalSize int

  Select @OriginalSize = size

  FROM sysfiles

  Where name = @LogicalFileName

  Select 'Original Size of ' + db_name() + ' LOG is ' +

  CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' +

  CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB'

  Create TABLE DummyTrans

  (DummyColumn char (8000) not null)

  DECLARE @Counter INT,

  @StartTime DATETIME,

  @TruncLog VARCHAR(255)

  Select @StartTime = GETDATE(),

  @TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY'

  DBCC SHRINKFILE (@LogicalFileName, @NewSize)

  EXEC (@TruncLog)

  -- Wrap the log if necessary.

  WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired

  AND @OriginalSize = (Select size FROM sysfiles Where name = @LogicalFileName)

  AND (@OriginalSize * 8 /1024) > @NewSize

  BEGIN -- Outer loop.

  Select @Counter = 0

  WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000))

  BEGIN -- update

  Insert DummyTrans VALUES ('Fill Log')

  Delete DummyTrans

  Select @Counter = @Counter + 1

  END

  Select 'Final Size of ' + db_name() + ' LOG is ' +

  CONVERT(VARCHAR(30),size) + ' 8K pages or ' +

  CONVERT(VARCHAR(30),(size*8/1024)) + 'MB'

  Drop TABLE DummyTrans

  SET NOCOUNT OFF

  exec sp_changeobjectowner 'tablename','dbo'

  Create PROCEDURE dbo.User_ChangeObjectOwnerBatch

  @OldOwner as NVARCHAR(128),

  @NewOwner as NVARCHAR(128)

  AS

  DECLARE @Name as NVARCHAR(128)

  DECLARE @Owner as NVARCHAR(128)

  DECLARE @OwnerName as NVARCHAR(128)

  DECLARE curObject CURSOR FOR

  select 'Name' = name,

  'Owner' = user_name(uid)

  from sysobjects

  where user_name(uid)=@OldOwner

  order by name

  OPEN curObject

  FETCH NEXT FROM curObject INTO @Name, @Owner

  WHILE(@@FETCH_STATUS=0)

  BEGIN

  if @Owner=@OldOwner

  set @OwnerName = @OldOwner + '.' + rtrim(@Name)

  exec sp_changeobjectowner @OwnerName, @NewOwner

  -- select @name,@NewOwner,@OldOwner

  close curObject

  deallocate curObject

  declare @i int

  set @i=1

  while @i<30

  insert into test (userid) values(@i)

  set @i=@i+1