Store a CAST to a variable in SQL

时间:2019-04-23 15:18:36

标签: sql sql-server select casting set

A column in SQL had data in an image format. I used CAST and the data spits out in text, which is all great. The problem is the column has HTML tags. I'm trying to strip away HTML tags from a column that has been casted.

I've created a function to remove the HTML tags but now I need to call the function on that casted column.

/* Converting the image to text */

SELECT cast(cast(note as varbinary(max)) as varchar (max)) note
FROM NOTES

/HTML Function/

CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
SET @Start = CHARINDEX('<',@HTMLText) SET @End = 
CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText)) 
SET @Length = (@End - @Start) + 1 WHILE @Start > 0
AND @End > 0
AND @Length > 0
BEGIN
SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
SET @Start = CHARINDEX('<',@HTMLText) SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
END
RETURN LTRIM(RTRIM(@HTMLText))
END
GO

THE PROBLEM CODE:

SELECT
       [Col1]
      ,[Col2]
      ,[Col3]
      ,[Col4]
      ,dbo.udf_StripHTML(cast(cast(note as varbinary(max)) as varchar (max)) note)
  FROM NOTES

How do I call the HTML function with the cast?

1 个答案:

答案 0 :(得分:0)

我认为这只是语法错误。这应该起作用:

SELECT
       [Col1]
      ,[Col2]
      ,[Col3]
      ,[Col4]
      ,[Note] = dbo.udf_StripHTML(cast(cast([note] as varbinary(max)) as varchar (max)))
FROM NOTES