實例:用SQLServer2005內置工具建立審查系統:能夠得到,如誰訪問了我們的數據、如何批准訪問權、以及我們如何對訪問進行監控,以防止某些人入侵、登錄數據或做他們不該做的事情。引用這裡
在SQL2005中處理交叉表: 關鍵字:PIVOT 和 UNPIVOT
示例: DECLARE @t TABLE ([日期] datetime,[時間] varchar(20),[售貨金額] int)
insert into @t select '2006-01-02','早上',50
union all select '2006-01-02','中午',20
union all select '2006-01-02','晚上',30
union all select '2006-01-02','零晨',40
union all select '2006-01-03','早上',40
union all select '2006-01-03','中午',60
union all select '2006-01-03','晚上',50
union all select '2006-01-03','零晨',50
union all select '2006-01-04','早上',80
union all select '2006-01-04','中午',60
union all select '2006-01-04','晚上',20
union all select '2006-01-04','零晨',40
--查詢
select * ,金額小計=(select sum(售貨金額) from @t where 日期=PT.日期 ) from @t as TAB
PIVOT
( max([售貨金額])
for [時間] in ([早上],[中午],[晚上],[零晨])
) as PT
--列不確定時: DECLARE @S VARCHAR(MAX)
SET @S=''
SELECT @S=@S+',['+時間+']' FROM @t
GROUP BY 時間
SET @S=STUFF(@S,1,1,'')
EXEC('
select 日期,'+@S+',金額小計=(select sum(售貨金額) from @t where 日期=PT.日期 ) from @t as TAB
PIVOT
( max(售貨金額)
for 時間 in ('+@S+')
) as PT
')
SQL2005中拆分列值,借用XML,簡單。見示例: -- 示例數據
DECLARE @t TABLE(id int, [values] varchar(100))
INSERT @t SELECT 1, 'aa,bb'
UNION ALL SELECT 2, 'aaa,bbb,ccc'
-- 查詢處理
SELECT A.id, B.value
FROM(
SELECT id, [values] = CONVERT(XML,
'
FROM @t
)A
OUTER APPLY(
SELECT value = N.v.value('.', 'varchar(100)')
FROM A.[values].nodes('/root/v') N(v)
)B 結果:
1 aa
1 bb
2 aaa
2 bbb
2 ccc
SQL2005中合並列值,見示例 -- 示例數據
DECLARE @t TABLE(id int, value varchar(10))
INSERT @t SELECT 1, 'aa'
UNION ALL SELECT 1, 'bb'
UNION ALL SELECT 2, 'aaa'
UNION ALL SELECT 2, 'bbb'
UNION ALL SELECT 2, 'ccc'