TSQL从格式/条件的动态查询中获取列名

时间:2018-02-18 17:26:57

标签: sql sql-server tsql

我需要从动态SQL中识别列的列表及其原始值。

示例:我有这个SQL语句:

@tsql = N'SELECT A.ID AS PROCESSID, COALESCE(STEP_ID,'''') AS programmid, NAME FROM DBO.TBL_LOG A'

根据this solution它只返回列名。我需要列名和原始值。

预期结果:

enter image description here

任何人都可以帮忙吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

下面的代码对我来说是暂时的,如果select子句中的语句过于复杂,那么它将无效。

;WITH CTE AS
    (
    SELECT NAME , SUBSTRING(LTRIM(@TSQL),7,CHARINDEX('FROM',LTRIM(@TSQL),0)-7) as QRY FROM sys.dm_exec_describe_first_result_set  (@TSQL, null, 0) 
    )
    ,COLPOS as
    (
    select NAME,QRY, CHARINDEX(NAME ,QRY,LEN(QRY) - CHARINDEX(REVERSE(NAME),REVERSE(QRY),0)- LEN(NAME)) AS POS
    FROM CTE
    )
    ,POS AS (
    SELECT NAME,QRY,POS,LAG(POS) OVER (order by (select 1)) LGPOS,LEAD(POS) OVER (order by (select 1)) LEADPOS  
    ,LAG(NAME) OVER (order by (select 1)) LGNAME
    FROM COLPOS
    )
    SELECT NAME , LTRIM(RTRIM(SUBSTRING (QRY,COALESCE(LGPOS+LEN(LGNAME),0),POS+LEN(NAME)-COALESCE(LGPOS+LEN(LGNAME),0)))) AS EXPRESSION
    FROM POS