數據開發庫-經典

1.按姓氏筆畫排序:
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //
從少到多

2.數據庫加密:
select encrypt('原始密碼')
select pwdencrypt('
原始密碼')
select pwdcompare('
原始密碼','加密後密碼') = 1--相同;否則不相同 encrypt('原始密碼')
select pwdencrypt('
原始密碼')
select pwdcompare('
原始密碼','加密後密碼') = 1--相同;否則不相同

3.取回表中字段:
declare @list varchar(1000),
@sql nvarchar(1000) 
select @list=@list+
','+b.name from sysobjects a,syscolumns b where a.id=b.id and a.name='A'
set @sql='select '+right(@list,len(@list)-1)+' from A
exec (@sql)

4.查看硬盤分區:
EXEC master..xp_fixeddrives

5.比較A,B表是否相等:
if (select checksum_agg(binary_checksum(*)) from A)
=
(select checksum_agg(binary_checksum(*)) from B)
print '
相等'
else
print '
不相等'

6.殺掉所有的事件探察器進程:
DECLARE hcforeach CURSOR GLOBAL FOR SELECT 'kill '+RTRIM(spid) FROM master.dbo.sysprocesses
WHERE program_name IN('SQL profiler',N'SQL 
事件探查器')
EXEC sp_msforeach_worker '?
'

7.記錄搜索:
開頭到N條記錄
Select Top N * From 
-------------------------------
NM條記錄(要有主索引ID)
Select Top M-N * From  Where ID in (Select Top M ID From ) Order by ID   Desc
----------------------------------
N
到結尾記錄
Select Top N * From  Order by ID Desc
案例
例如1:一張表有一萬多條記錄,表的第一個字段 RecID 是自增長字段, 寫一個SQL語句, 找出表的第31到第40個記錄。

 select top 10 recid from A where recid not  in(select top 30 recid from A)

分析:如果這樣寫會產生某些問題,如果recid在表中存在邏輯索引。

    select top 10 recid from A where……是從索引中查找,而後面的select top 30 recid from A則在數據表中查找,這樣由於索引中的順序有可能和數據表中的不一致,這樣就導致查詢到的不是本來的欲得到的數據。

解決方案

1, order by select top 30 recid from A order by ricid 如果該字段不是自增長,就會出現問題

2, 在那個子查詢中也加條件:select top 30 recid from A where recid>-1

2:查詢表中的最後以條記錄,並不知道這個表共有多少數據,以及表結構。
set @s = 'select top 1 * from T   where pid not in (select top ' + str(@count-1) + ' pid from  T)'

print @s      exec  sp_executesql  @s

9:獲取當前數據庫中的所有用戶表
select Name from sysobjects where xtype='u' and status>=0

10:獲取某一個表的所有字段
select name from syscolumns where id=object_id('表名')

select name from syscolumns where id in (select id from sysobjects where type = 'u' and name = '表名')

兩種方式的效果相同

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章