将函数插入SQL语句

时间:2018-04-09 12:59:10

标签: sql-server tsql stored-functions

全新的功能。从其他人那里收到函数来解决数据拉动中的html标签。不知道如何将此代码合并到我的查询中。

CREATE FUNCTION [dbo].[mcl_RemoveVisionMemoFormat] 
(@String NVARCHAR(MAX)) 
 RETURNS NVARCHAR(MAX) 
AS 
BEGIN 
declare @start int, 
        @end int, 
        @length int 

while charindex('<', @string) > 0 and charindex('>', @string, charindex('<', 
@string)) > 0 
begin 
    select  @start  = charindex('<', @string),  
            @end    = charindex('>', @string, charindex('<', @string)) 
    select @length = (@end - @start) + 1 

    if @length > 0 
    begin 
        select @string = stuff(@string, @start, @length, '') 
        end 
    end 

return replace(@string , '&nbsp;' , ' ') 
END

需要将上面的函数添加到基本的SELECT语句

SELECT LD.WBS1 as [Project Number], LD.Name, LD.Comment, LD.TransDate as 
[Comment Date]
FROM LD
WHERE (((LD.Comment) Is Not Null))
ORDER BY LD.TransDate DESC;

非常感谢!

1 个答案:

答案 0 :(得分:0)

您的问题是严格如何使用列作为参数

在查询中使用标量函数

为此,您只需将该函数添加到select语句并传入列。

Select [schema].[ScalarFunction](column) as [ColumnName] from [schema].table

对于您提供的查询,您只需添加函数[dbo]。[mcl_RemoveVisionMemoFormat],然后在括号中添加列名LD.Comment

SELECT LD.WBS1 as [Project Number], LD.Name, LD.Comment, LD.TransDate as [Comment Date], [dbo].[mcl_RemoveVisionMemoFormat](LD.Comment) as [CommentWithoutVisionMemoFormat]
FROM LD
WHERE LD.Comment IS NOT NULL
ORDER BY LD.TransDate DESC;