Hello! Happy Friday!
I have a question....I have some SQL that I want to make into a function; I want to only pass in the String to parse, but get an error for using DECLARE when I try to execute it...
Could someone please assist me in how to make this code a function and still only passing in the string?
If I execute that code it works, but if I uncomment the 'CREATE FUNTION...' and then comment the code to declare the string back in, I'm getting the error...
Thoughts and insight are greatly appreciated!
Thanks much!
-jiggyg
I have a question....I have some SQL that I want to make into a function; I want to only pass in the String to parse, but get an error for using DECLARE when I try to execute it...
Could someone please assist me in how to make this code a function and still only passing in the string?
Code:
/*
CREATE FUNCTION [dbo].[parseAEcountTreeString](@String varchar(255))
RETURNS TABLE
AS RETURN
*/
--/*
--declare the String
DECLARE @String varchar(255)
SET @String = 'BLOCK A/ACC - CONVENTION CENTER/RETAIL/AIS'
--*/
--declare the delimeter between each Info
DECLARE @Delimeter char(1)
SET @Delimeter = '/'
--Parse the string and insert each Parsed Item into the @tblString table
DECLARE @tblString TABLE(Parsed varchar(255))
DECLARE @Parsed varchar(255)
DECLARE @StartPos int, @Length int
WHILE LEN(@String) > 0
BEGIN
SET @StartPos = CHARINDEX(@Delimeter, @String)
IF @StartPos < 0 SET @StartPos = 0
SET @Length = LEN(@String) - @StartPos - 1
IF @Length < 0 SET @Length = 0
IF @StartPos > 0
BEGIN
SET @Parsed = SUBSTRING(@String, 1, @StartPos - 1)
SET @String = SUBSTRING(@String, @StartPos + 1, LEN(@String) - @StartPos)
END
ELSE
BEGIN
SET @Parsed = @String
SET @String = ''
END
INSERT @tblString (Parsed) VALUES(@Parsed)
END
--Show all Parsed Items in the @tblString table
SELECT * FROM @tblString
If I execute that code it works, but if I uncomment the 'CREATE FUNTION...' and then comment the code to declare the string back in, I'm getting the error...
Thoughts and insight are greatly appreciated!
Thanks much!
-jiggyg