sql 常用 系統語句

來源:互聯網
上載者:User
--約束條件

ALTER TABLE doc_exd WITH NOCHECK
ADD CONSTRAINT exd_check CHECK (column_a > 1)

--禁用約束

ALTER TABLE B_base NOCHECK CONSTRAINT b_base_check

--啟用約束

 WITH CHECK CONSTRAINT

--查看約束

sp_helpconstraint b_enterbase

---減小日誌

DUMP TRANSACTION Tb_hongDataBase WITH NO_LOG
BACKUP LOG Tb_hongDataBase WITH NO_LOG
DBCC SHRINKDATABASE(Tb_hongDataBase)
EXEC sp_dboption 'Tb_hongDataBase', 'autoshrink', 'TRUE'

---清除重複記錄

delete 表 where sn not in(select min(sn) from 表 group by col1,col2)

---更改表的所有者

exec sp_changeobjectowner 'hongkang.T_SellPlan','dbo'

---觸發器

CREATE TRIGGER tri_a ON a
FOR INSERT,UPDATE,DELETE
AS
IF EXISTS (SELECT * FROM deleted)
BEGIN
 DELETE FROM b WHERE .....--(所有欄位與deleted表相等的條件)
END
IF EXISTS (SELECT * FROM inserted)
BEGIN
 INSERT INTO b SELECT * FROM inserted 
END

 

1. 查看資料庫的版本

select @@version

2. 查看資料庫所在機器作業系統參數

exec master..xp_msver

3. 查看資料庫啟動的參數

sp_configure

4. 查看資料庫啟動時間

select convert(varchar(30),login_time,120) from master..sysprocesses where spid=1

查看資料庫伺服器名和執行個體名

print ''Server Name...............: '' + convert(varchar(30),@@SERVERNAME)
print ''Instance..................: '' + convert(varchar(30),@@SERVICENAME)

5. 查看所有資料庫名稱及大小

sp_helpdb

重新命名資料庫用的SQL

sp_renamedb ''old_dbname'', ''new_dbname''

6. 查看所有資料庫使用者登入資訊

sp_helplogins

查看所有資料庫使用者所屬的角色資訊

sp_helpsrvrolemember

修複遷移伺服器時孤立使用者時,可以用的fix_orphan_user指令碼或者LoneUser過程

更改某個資料對象的使用者屬主

sp_changeobjectowner [@objectname =] ''object'', [@newowner =] ''owner''

注意: 更改對象名的任一部分都可能破壞指令碼和預存程序。

把一台伺服器上的資料庫使用者登入資訊備份出來可以用add_login_to_aserver指令碼

7. 查看連結的伺服器

sp_helplinkedsrvlogin

查看遠端資料庫使用者登入資訊

sp_helpremotelogin

8.查看某資料庫下某個資料對象的大小

sp_spaceused @objname

sp_msforeachtable 'exec sp_spaceused "?"'

還可以用sp_toptables過程看最大的N(預設為50)個表

查看某資料庫下某個資料對象的索引資訊

sp_helpindex @objname

還可以用SP_NChelpindex過程查看更詳細的索引情況
SP_NChelpindex @objname

clustered索引是把記錄按物理順序排列的,索引占的空間比較少。
對索引值DML操作十分頻繁的表我建議用非clustered索引和約束,fillfactor參數都用預設值。
查看某資料庫下某個資料對象的的約束資訊
sp_helpconstraint @objname

9.查看資料庫裡所有的預存程序和函數

use @database_name
sp_stored_procedures
查看預存程序和函數的原始碼
sp_helptext ''@procedure_name''

查看包含某個字串@str的資料對象名稱

select distinct object_name(id) from syscomments where text like ''%@str%''

建立加密的預存程序或函數在AS前面加WITH ENCRYPTION參數

解密加密過的預存程序和函數可以用sp_decrypt過程

10.查看資料庫裡使用者和進程的資訊

sp_who
查看SQL Server資料庫裡的活動使用者和進程的資訊
sp_who ''active''
查看SQL Server資料庫裡的鎖的情況
sp_lock

進程號1--50是SQL Server系統內部用的,進程號大於50的才是使用者的串連進程.
spid是進程編號,dbid是資料庫編號,objid是資料對象編號
查看進程正在執行的SQL語句
dbcc inputbuffer ()

推薦大家用經過改進後的sp_who3過程可以直接看到進程啟動並執行SQL語句
sp_who3

檢查死結用sp_who_lock過程

sp_who_lock

11.收縮資料庫記錄檔的方法

收縮簡單復原模式資料庫日誌,收縮後@database_name_log的大小單位為M
backup log @database_name with no_log
dbcc shrinkfile (@database_name_log, 5)
12.分析SQL Server SQL 陳述式的方法:

set statistics time {on | off}
set statistics io {on | off}
圖形方式顯示查詢執行計畫

在查詢分析器->查詢->顯示估計的評估計劃(D)-Ctrl-L 或者點擊工具列裡的圖形

文本方式顯示查詢執行計畫
set showplan_all {on | off}

set showplan_text { on | off }
set statistics profile { on | off }

13.出現不一致錯誤時,NT事件檢視器裡出3624號錯誤,修複資料庫的方法

先注釋掉應用程式裡引用的出現不一致性錯誤的表,然後在備份或其它機器上先恢複然後做修複操作

alter database [@error_database_name] set single_user

修複出現不一致錯誤的表

dbcc checktable(''@error_table_name'',repair_allow_data_loss)

或者可惜選擇修複出現不一致錯誤的小型資料庫名

dbcc checkdb(''@error_database_name'',repair_allow_data_loss)
alter database [@error_database_name] set multi_user
CHECKDB 有3個參數:
repair_allow_data_loss 包括對行和頁進行分配和取消分配以改正分配錯誤、結構行或頁的錯誤,
以及刪除已損壞的文字物件,這些修複可能會導致一些資料丟失。
修複操作可以在使用者事務下完成以允許使用者復原所做的更改。
如果復原修複,則資料庫仍會含有錯誤,應該從備份進行恢複。
如果由於所提供修複等級的緣故遺漏某個錯誤的修複,則將遺漏任何取決於該修複的修複。
修複完成後,請備份資料庫。
repair_fast 進行小的、不耗時的修複操作,如修複非叢集索引中的附加鍵。
這些修複可以很快完成,並且不會有遺失資料的危險。
repair_rebuild 執行由 repair_fast 完成的所有修複,包括需要較長時間的修複(如重建索引)。
執行這些修複時不會有遺失資料的危險。

事務

CREATE PROCEDURE  a
@i int
 AS
begin
 set XACT_ABORT on
 begin tran
   update aa set col1=col1-@i where id=1
   update aa set col1=col1+@i where id =2
 commit tran
end

GO

Begin
update aa set col1=col1-@i where id=1
 if @@error>0
   begin
    Rollback Tran
    Return
   end
update aa set col1=col1+@i where id =2
 if @@error>0
    Rollback Tran
 else
    Commit Tran

清空資料庫

--先禁用所有外鍵約束
exec sp_msforeachtable "alter table ? nocheck CONSTRAINT all"

--禁止所有觸發器
exec sp_msforeachtable "alter table ? disable trigger all"

--然後刪除資料
/*exec sp_msforeachtable @command1='truncate table ?'
                       ,@whereand='and name not like ''sys%''
                                   and name not in(''dtproperties'',''特殊表2'',''特殊表3'')'*/
  exec sp_msforeachtable @command1='truncate table ?',
 @whereand=' and objectproperty(o.id,''TableHasForeignRef'')=0'
  exec sp_msforeachtable @command1='delete from ?',
 @whereand=' and objectproperty(o.id,''tablehasforeignref'')=1'
--再啟用所有外鍵約束
exec sp_msforeachtable "alter table ? check constraint all"

--啟用所有觸發器
exec sp_msforeachtable "alter table ? enable trigger all"

 

壓縮資料庫

--1.清空日誌
DUMP TRANSACTION 資料庫 WITH  NO_LOG

--2.截斷交易記錄
BACKUP LOG 資料庫 WITH NO_LOG

--3.收縮資料庫檔案
DBCC SHRINKDATABASE(資料庫)

--4.設定自動收縮
ALTER DATABASE 資料庫 SET AUTO_SHRINK ON

資料庫當前的串連資料

select count(1) from master..sysprocesses where status <>'background' 

SQL匯出

exec master..xp_cmdshell 'bcp "select * from 資料庫名.dbo.表名" queryout "C:/xxx.xls" -c -S 伺服器 -U sa -P 密碼'

查詢另一資料庫

select * from openrowset('sqloledb','另一個sql伺服器名或ip地址';'使用者名稱';'密碼',要查詢的資料庫名.dbo.要查詢的表名)

交叉表執行個體

建表:

在查詢分析器裡運行:

CREATE TABLE [Test] (

       [id] [int] IDENTITY (1, 1) NOT NULL ,

       [name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,

       [subject] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,

       [Source] [numeric](18, 0) NULL

) ON [PRIMARY]

GO

INSERT INTO [test] ([name],[subject],[Source]) values (N'張三',N'語文',60)

INSERT INTO [test] ([name],[subject],[Source]) values (N'李四',N'數學',70)

INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'英語',80)

INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'數學',75)

INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'語文',57)

INSERT INTO [test] ([name],[subject],[Source]) values (N'李四',N'語文',80)

INSERT INTO [test] ([name],[subject],[Source]) values (N'張三',N'英語',100)

Go

 

交叉表語句的實現:

--用於:交叉表的列數是確定的

select name,sum(case subject when '數學' then source else 0 end) as '數學',

          sum(case subject when '英語' then source else 0 end) as '英語',

            sum(case subject when '語文' then source else 0 end) as '語文'

from test

group by name

 

 

--用於:交叉表的列數是不確定的

declare @sql varchar(8000)

set @sql = 'select name,'

 

select @sql = @sql + 'sum(case subject when '''+subject+'''

                          then source else 0 end) as '''+subject+''','

  from (select distinct subject from test) as a

 

select @sql = left(@sql,len(@sql)-1) + ' from test group by name'

exec(@sql)

go

匯出表結構

SELECT
表名=case when a.colorder=1 then d.name else '' end,
表說明=case when a.colorder=1 then isnull(f.value,'') 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,''),
欄位說明=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 sysproperties g on a.id=g.id and a.colid=g.smallid 
left join sysproperties f on d.id=f.id and f.smallid=0
--where d.name='要查詢的表'    --如果只查詢指定表,加上此條件
order by a.id,a.colorder

產生隨機數
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RandTb]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[RandTb]
GO
CREATE TABLE [dbo].[RandTb] (RandNo varchar(50) primary key)
GO
declare
@No char(20),
@Num int,
@Stime datetime,
@Etime datetime
set nocount on
set @Stime = getdate()
set @Num=0
while @Num<50000
begin
 --set @No = right((cast((rand()*10000000000000000) as bigint)),15)  --數字
 set @No = right(Replace(newid(),'-',''),15)              --字母
 if not exists(select 1 from Randtb where RandNo=@No)
 begin 
  insert into RandTb values(@No)
  set @Num=@Num+1
 end
end
set @Etime = getdate()
set nocount off
print datediff(ms,@Stime,@Etime)
drop table [dbo].[RandTb]

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.