假設有一個表
id , path
1 , '2001/1/A'
2 , '2001/2/B'
3 , '2001/1/C'
path 代表 年/月/公司
我要怎麼建立一個 VIEW 叫 report
用 起來像這樣
select year,month,com from report where year = 2001 and com ='A'
CREATE TABLE TableX
(Id int,Path varchar(20));
INSERT INTO TableX
VALUES
(1 , '2001/1/A'),
(2 , '2001/12/Bl'),
(3 , '2001/1/CkF');
CREATE VIEW report
AS SELECT Id,Path,
SUBSTRING(Path,0,First) AS 'year',
SUBSTRING(Path,First+1,Second-First-1) AS 'month',
SUBSTRING(Path,Second+1,LEN(Path)-Second) AS 'com'
FROM (
SELECT *,
CHARINDEX('/', Path) AS 'First',
LEN(Path) - CHARINDEX('/', REVERSE(Path))+1 AS 'Second'
FROM TableX) AS M
快又漂亮 還有DEMO 學習了 :)
CREATE VIEW report
AS SELECT Id,Path,
d.vals.value('(/TR/TD)[1]','VARCHAR(10)') AS 'year',
d.vals.value('(/TR/TD)[2]','VARCHAR(10)') AS 'month',
d.vals.value('(/TR/TD)[3]','VARCHAR(10)') AS 'com'
FROM (
SELECT Id,Path,
CAST('<TR><TD>' + REPLACE(Path, '/', '</TD><TD>') + '</TD></TR>' AS xml) vals
FROM TableX) AS d
DECLARE @TmpTable TABLE
(
id int,
path varchar(20)
)
insert into @TmpTable values (1,'2001/1/A')
insert into @TmpTable values (2,'2001/2/B')
insert into @TmpTable values (3,'2001/1/C')
select id,SUBSTRING(path,0,CHARINDEX('/',path)) as [year]
,replace(SUBSTRING(path,5,(len(path)-CHARINDEX('/',REVERSE(path))+1)-(CHARINDEX('/',path))),'/','') as [month]
,replace(SUBSTRING(path,(len(path)-CHARINDEX('/',REVERSE(path))+1),CHARINDEX('/',path)),'/','') as [com]
from @TmpTable
驗證查詢結果
建立一個 VIEW 叫 report
CREATE VIEW [dbo].[report]
AS
select id,SUBSTRING(path,0,CHARINDEX('/',path)) as [year]
,replace(SUBSTRING(path,5,(len(path)-CHARINDEX('/',REVERSE(path))+1)-(CHARINDEX('/',path))),'/','') as [month]
,replace(SUBSTRING(path,(len(path)-CHARINDEX('/',REVERSE(path))+1),CHARINDEX('/',path)),'/','') as [com]
from @yourTable
GO