Parse QueryString in SQL Server 2005

末鹿安然 提交于 2019-12-11 00:02:14

问题


Is there a simple way to parse QueryString parameters (e.g. foo=bar&temp=baz) in SQL Server?

What I need in the end is a "table" with the name/value pairs.

| foo  | bar |
| temp | baz |

While it would be simple in the above example it becomes harder if the strings start to contain escaped characters (e.g. %3D) and even tougher when UTF-8 is involved.

Any existing solutions? An implementation of URLDecode for SQL Server would be heaven on earth.


回答1:


So to parse the query string, just use a CTE in a function. Here is the code.

CREATE FUNCTION dbo.SplitQueryString (@s varchar(8000))
RETURNS table
AS
RETURN (
    WITH splitter_cte AS (
      SELECT CHARINDEX('&', @s) as pos, 0 as lastPos
      UNION ALL
      SELECT CHARINDEX('&', @s, pos + 1), pos
      FROM splitter_cte
      WHERE pos > 0
      ),
    pair_cte AS (
    SELECT chunk,
           CHARINDEX('=', chunk) as pos
    FROM (
        SELECT SUBSTRING(@s, lastPos + 1,
                         case when pos = 0 then 80000
                         else pos - lastPos -1 end) as chunk
        FROM splitter_cte) as t1
  )
    SELECT substring(chunk, 0, pos) as keyName,
           substring(chunk, pos+1, 8000) as keyValue
    FROM pair_cte
)
GO

declare @queryString varchar(2048)
set @queryString = 'foo=bar&temp=baz&key=value';
SELECT *
  FROM dbo.SplitQueryString(@queryString)
OPTION(MAXRECURSION 0);

when run produces the following output.

keyName  keyValue
-------  --------
foo      bar
temp     baz
key      value
(3 row(s) affected)

I believe that this will do exactly what you are asking.



来源:https://stackoverflow.com/questions/8986150/parse-querystring-in-sql-server-2005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!