특정 문자로 구분되는 데이터 분리 Query
DECLARE @p VARCHAR(MAX)
SET @p = '0001,0003,0005'
IF @p IS NOT NULL OR @p != ''
BEGIN
IF RIGHT(@p, 1) = @delimiter
BEGIN
SET @p = LEFT(@p, LEN(@p) - 1)
END
END
SELECT CONVERT(VARCHAR(10), Y.item.query('text()')) AS val
FROM (
SELECT CONVERT(xml, '<r>' + replace(@p, ',', '</r><r>') + '</r>') AS xitem
) X
CROSS APPLY X.xitem.nodes('/r') AS Y(item)
The table is example is:
TableName: NumberTable
NumberCols |
first |
second |
third |
fourth |
fifth |
Output : first,second,third,fourth,fifth
Option 1: This is the smartest way.DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' , '') + NumberCols
FROM NumberTable
SELECT @listStr
Please make a note that COALESCE returns the first NOT NULL value from the argument list we pass.
Option 2: This is the smart but not the best way; though I have seen similar code many times.DECLARE @listStr VARCHAR(MAX)
SET @listStr = ''
SELECT @listStr = @listStr + NumberCols + ','
FROM NumberTable
SELECT SUBSTRING(@listStr , 1, LEN(@listStr)-1)
'Database > MS SQL' 카테고리의 다른 글
Procedure에서 PRINT(출력) 바로 내보내기 (0) | 2012.02.16 |
---|---|
SQL Server OPENROWSET (0) | 2012.02.16 |
sp_who2 LastBatch 문자열 오류 수정 (0) | 2012.02.05 |
SQL Profiler 결과 데이터베이스로 읽어오기 (0) | 2012.02.04 |
MS SQL Server 2008 Excel 파일 불러오기 (0) | 2011.11.03 |