0

好吧,我一直在爲此亂搞一段時間,但似乎無法使其發揮作用。那麼,或者它是不可能的剝離XML字符串中的標籤並將其用作別名

鑑於以下T-SQL我想剝離<>標記並使用裏面的內容作爲別名。可能?我正在考慮嵌套替換剝離它,但不知道如何使用結果作爲別名。整個目標是在SET語句中定義html標記,並讓它自動填充表變量中的別名和列指示符。如果有一個更好/更簡單的方法,不像xpath那樣涉及,我是開放的。

Use Database 
DECLARE @First VARCHAR(15), @Second VARCHAR(15),@XMLTag varchar(15) 
SET @First = '<InstrumentID>' 
SET @Second = '</InstrumentID>' 
SET @XMLTag = Replace(Replace,@first,'<',''),@first,'>','') 

select * 
from 
(
     SELECT out_interface_id, msg_id , 
     SUBSTRING(xml_msg, CHARINDEX(@First, xml_msg) + LEN(@First), 
       CHARINDEX(@Second, xml_msg) - 
       CHARINDEX(@First, xml_msg) - 
       LEN(@First)) as @XMLTag, 
     msg_type, xml_msg, CAST(xml_msg AS XML) as [Quick_XML], 
     date_received,status, last_modified, environment, 
     transaction_closed_date 
     from Table1 with (nolock) 
     where msg_type in ('BALMIS','ACCTV21') 
     and date_received >= CAST(GETDATE() -1 as DATE) 
     and date_received < CAST(GETDATE() as DATE) 
) x 
where [email protected] = 'ABC123' 
order by date_received desc 
+0

@XMLtag的assign語句存在語法錯誤。考慮修復它。 – AXMIM

+0

要使別名正常工作,您需要動態SQL – AXMIM

回答

1

要擁有動態別名,您需要動態SQL。

在VARCHAR(MAX)變量中構建查詢後,可以使用 過程sp_executesql來執行構建的查詢。

DECLARE @DynamicSQL NVARCHAR(MAX) 
DECLARE @First VARCHAR(15) 
SELECT @First = '<InstrumentID>' 

SELECT @DynamicSQL = 'SELECT ''WhatEver'' AS ' + REPLACE(REPLACE(@First, '<', ''), '>', '') + ' 
         FROM [InsertYourFromStatementHere] 
         WHERE [email protected] = ''ABC123'' 
         ORDER BY date_received DESC' 

PRINT @DynamicSQL 

EXEC sp_executesql @DynamicSQL 

執行上面的查詢,它會失敗,因爲[InsertYourFromStatementHere]和x不存在。但是,您將在輸出中看到生成的動態SQL。修改查詢,直到你得到一個運行並做你想要的。

請注意,這爲SQL注入打開了大門。