我有以下选择查询(使用SQL Server 2017):
SELECT PAYMENT_INFO
FROM CHECK_PAYMENT
WHERE (PAYMENT_FISCAL_DATE = '01/19/2018')
AND (TENDER_MEDIA_NAME LIKE 'PaymentCard%')
ORDER BY VOID, TENDER_MEDIA_NAME
输出是一个非常长的分号分隔字符串,我想只返回前两个字段。
当前输出:
AmericanExpress;XXXXXXXXXXX4111;;;;41.47;8.00...............
MasterCard;XXXXXXXXXXXX7971;;;;40.22;10.00................
Visa;XXXXXXXXXXXX6302;;;;11.94;0.00....................
期望的输出:
AmericanExpress;XXXXXXXXXXX4111
MasterCard;XXXXXXXXXXXX7111
Visa;XXXXXXXXXXXX6111
如果可能的话,我希望将它们分成两列。
我查看过堆栈并发现了类似的问题,但没有找到有效的答案,或者我可以弄清楚如何修改我的情况。
答案 0 :(得分:1)
创建以下功能。
CREATE FUNCTION dbo.ColumnSplitter
(
@String VARCHAR(MAX),
@NroSubString INT,
@Separator VARCHAR(5)
)
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @St INT = 0, @End INT = 0, @Ret VARCHAR(MAX)
SET @String = @String + @Separator
WHILE CHARINDEX(@Separator, @String, @End + 1) > 0 AND @NroSubString > 0
BEGIN
SET @St = @End + 1
SET @End = CHARINDEX(@Separator, @String, @End + 1)
SET @NroSubString = @NroSubString - 1
END
IF @NroSubString > 0
SET @Ret = ''
ELSE
SET @Ret = SUBSTRING(@String, @St, @End - @St)
RETURN @Ret
END
GO
然后在查询中使用它。
SELECT dbo.ColumnSplitter(PAYMENT_INFO, 1, ';') as FirstColumn,
dbo.ColumnSplitter(PAYMENT_INFO, 2, ';') as SecondColumn
FROM CHECK_PAYMENT
WHERE (PAYMENT_FISCAL_DATE = '01/19/2018')
AND (TENDER_MEDIA_NAME LIKE 'PaymentCard%')
答案 1 :(得分:0)
这将返回单个列,其值以分号分隔:
declare @example as table (
exampleid int identity(1,1) not null primary key clustered
, value_ nvarchar(255) not null
);
insert into @example (value_)
select 'AmericanExpress;XXXXXXXXXXX4111;;;;41.47;8.00...............' union all
select 'MasterCard;XXXXXXXXXXXX7971;;;;40.22;10.00................' union all
select 'Visa;XXXXXXXXXXXX6302;;;;11.94;0.00....................'
select substring(value_, 0, charindex(';', value_, charindex(';', value_) + 1)) Payment_Info
from @example
答案 2 :(得分:0)
SELECT LEFT(PAYMENT_INFO,
CHARINDEX(';', PAYMENT_INFO,
CHARINDEX(';', PAYMENT_INFO) + 1))
FROM CHECK_PAYMENT
WHERE (PAYMENT_FISCAL_DATE = '01/19/2018')
AND (TENDER_MEDIA_NAME LIKE 'PaymentCard%')
ORDER BY VOID, TENDER_MEDIA_NAME