本文介绍了如何在SQL中拆分查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用=符号拆分查询,



输入为

I want to split a query using "=" symbol,

Input is "

Testing_TestEnvironment=open=2017-03-23





我试图获得输出,但还有其他方法可以达到这个目的。



"

I have tried to get output, But is there any other way to achieve this.

SELECT  Reverse(ParseName(Replace(Reverse(filter_date), '=','.'), 1)) As [machinename], Reverse(ParseName(Replace(Reverse(filter_date), '=','.'), 2)) As [status] , Reverse(ParseName(Replace(Reverse(filter_date), '=','.'), 3)) As [date] 
 FROM  (Select  filter_date from tbl_AlertNotify where alert_title = 'Size Monitor') As [duptable] 





输出:

................................................. .....

机器名称状态日期

.......................... ............................

Testing_TestEnvironment开启2017-03-23







请改变我的疑问



我尝试了什么:





output:
......................................................
machinename status date
......................................................
Testing_TestEnvironment open 2017-03-23



Kindly alter my query

What I have tried:

SELECT  Reverse(ParseName(Replace(Reverse(filter_date), '=','.'), 1)) As [machinename], Reverse(ParseName(Replace(Reverse(filter_date), '=','.'), 2)) As [status] , Reverse(ParseName(Replace(Reverse(filter_date), '=','.'), 3)) As [date] 
 FROM  (Select  filter_date from tbl_AlertNotify where alert_title = 'Size Monitor') As [duptable] 

推荐答案

CREATE FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
	-- a comment in the source
	DECLARE @source varchar(max) = 'http://www.sqlservercentral.com/blogs/querying-microsoft-sql-server/2013/09/19/how-to-split-a-string-by-delimited-char-in-sql-server/'
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1
       
        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)
        
    END 
    RETURN 
END

您可以这样称呼:

Which you would call like this:

select * from dbo.fnSplitString('Testing_TestEnvironment=open=2017-03-23','=')



或者,如果您希望按预期输出格式化结果,请按以下方式调用:


Or if you want the results formatted as per your expected output then call it like this:

SELECT [1] AS [machinename], [2] AS [status], [3] AS [date]
FROM (
    select ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS X, * from dbo.fnSplitString('Testing_TestEnvironment=open=2017-03-23','=')
) as qry
PIVOT
(
    MAX(splitdata)
    FOR [X] IN ([1],[2],[3])
)AS pvt



这篇关于如何在SQL中拆分查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 04:26