Avatar of koldstar
koldstar

asked on 

SQL: Build SELECT with LOOP

Hi.

I'm trying to union some SELECTS to one resultset. The code below works, but displays in two resultsets.
I thought I could just write something like the 4 lines below, but it gives me an error.

if (@pos <> 0)
begin
 UNION ALL
end

Please help!




--THIS CODE WORKS, BUT DISPLAYS IN TWO REULST SETS!
 
ALTER PROCEDURE dbo.Search (@SearchFrase NVARCHAR(255))
AS
 
 declare @String nvarchar (4000)
 declare @Delimiter nvarchar (10)
 declare @NextString nvarchar(4000)
 declare @Pos int
 declare @NextPos int
 declare @CommaCheck nvarchar(1)
 
  --Initialize
 Set @String = @SearchFrase
 SET @Delimiter = ' '
 set @NextString = ''
 set @CommaCheck = right(@String,1) 
 
 --Check for trailing Comma, if not exists, INSERT
 --if (@CommaCheck <> @Delimiter )
 set @String = @String + @Delimiter
 
 --Get position of first Comma
 set @Pos = charindex(@Delimiter,@String)
 set @NextPos = 1
 
 
 --Loop while there is still a comma in the String of levels
 while (@pos <>  0)  
 begin
  set @NextString = substring(@String,1,@Pos - 1)
 
	   set @SearchFrase = @NextString
 
		set @String = substring(@String,@pos +1,len(@String))
  
		set @NextPos = @Pos
		set @pos  = charindex(@Delimiter,@String)
 
		 ---brugerdanne kode
		SELECT Navn AS SearchTitle ,dbo.fnStripTags(Content) AS SearchDescription  ,'http://creativemedia.dk/default.asp?MenuId=' + LTRIM(Id) AS link FROM V_content WHERE Navn LIKE '%' + @SearchFrase + '%'  OR Content LIKE '%' + @SearchFrase + '%'  OR Title LIKE '%' + @SearchFrase + '%'  OR Meta_Description LIKE '%' + @SearchFrase + '%' 
		UNION ALL 
		SELECT Overskrift AS SearchTitle ,dbo.fnStripTags(Nyhed) AS SearchDescription  ,'http://creativemedia.dk/default.asp?MenuId=F_5&NyhedId=' + LTRIM(Id) AS link FROM Live_Nyheder WHERE Overskrift LIKE '%' + @SearchFrase + '%'  OR Nyhed LIKE '%' + @SearchFrase + '%' 
 
		--if (@pos <> 0)
		--begin
			--UNION ALL
		--end
		
 end

Open in new window

SQL

Avatar of undefined
Last Comment
koldstar

8/22/2022 - Mon