1

我需要组合字段,然后修剪文本字段中间的多余空格。使用 Access 对我来说很容易,但创建 SQL 函数却让我望而却步。这就是我在 Access 中的做法,谁能帮我创建一个 SQL 函数?

在 VBA 访问查询中,我可以在查询中使用以下代码执行此操作:

FullTrim([tblLeadsResi].[House Number] & [tblLeadsResi].[Street] & " " & 
    [tblLeadsResi].[Street Suffix] & " " & [tblLeadsResi].[Post-directional] & 
    IIf(Not IsNull([tblLeadsResi].[Apartment Number])," #" & 
    [tblLeadsResi].[Apartment Number],""))

Access中的模块代码:(基本上,如果它是一个双空格,它不会添加第一个空格)

Public Function FullTrim(stText As String) As Variant
Dim intLen As Integer, stPart As String, stBlank As String, stNewText As String

    '   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    '   ++++    Takes any spaces away from a Text Value     ++++
    '   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    If IsNull(stText) Or stText = "" Then
        FullTrim = ""
    Else
        For intLen = 1 To (Len(stText) - 1)
            stPart = Mid(stText, intLen, 1)
            stBlank = Mid(stText, intLen, 2)
            If stBlank <> "  " Then
                stNewText = stNewText & stPart
            End If
        Next intLen

        intLen = Len(stText)
        stPart = Mid(stText, intLen, 1)
        stNewText = stNewText & stPart

        stNewText = Trim(stNewText)
        FullTrim = stNewText
    End If
End Function
4

2 回答 2

1

创建

CREATE FUNCTION dbo.FullTrim(@Value NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @Subs NVARCHAR(6)
    SET @Subs = '~@$$#%' -- Make this some string you will never have in your data
    RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(@Value, '  ', ' ' + @Subs), @Subs + ' ', ''), @Subs, '')))
END

用法

SELECT dbo.FullTrim('  This is a     string      with    many spaces ')

结果

This is a string with many spaces
于 2012-06-24T03:14:01.017 回答
0

试试这个功能:

CREATE FUNCTION [dbo].[FullTrim](@text nvarchar(max))
RETURNS nvarchar(max)
AS
BEGIN
    RETURN replace(@text, ' ', '')
END

...然后传递所有连接在一起的字段,例如:

SELECT dbo.FullTrim([tblLeadsResi.House Number] + [tblLeadsResi.Street] + ...) 
FROM tblLeadsResi
...
于 2012-06-24T03:03:30.180 回答