Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 conditional join..kinda

Author  Topic 

shay1975
Starting Member

2 Posts

Posted - 2006-08-23 : 01:20:24
Bascially what I have is a search term that may or may not be entered. If the search term is space delimited, I extract the words into a table variable and join on the table using a like statement. This all works fine, but what if no search term is entered, I don't want to perform this join as it will return nothing. Other than use and if/else statement around the whole sql statement and having to maintain several slightly modified versions of the sql statement, is there a better way of doing this? Thanks in advance

See code below
DECLARE @word VARCHAR(80)
SET @FundName = RTRIM(LTRIM(@FundName)) + ' '

WHILE @FundName <> ''
BEGIN
SET @spaceat = CHARINDEX( ' ', @FundName )
SET @word = SUBSTRING(@FundName, 1, @spaceat-1 )
INSERT INTO @FN1 VALUES(@FundName)
SET @FundName = SUBSTRING(@FundName, @spaceat+1, LEN(@FundName) )
END

join on table variable

JOIN @FN1 FN ON (BI.FundName like '%' + FN.word + '%' OR FC.Name like '%' + FN.word + '%')

chiragkhabaria
Master Smack Fu Yak Hacker

1907 Posts

Posted - 2006-08-23 : 01:32:42
I guess you are better of using this split function ..

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CrackInRows]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[CrackInRows]
GO
CREATE FUNCTION [dbo].[CrackInRows] (@delim varchar(1), @Phrase2Crack as varchar(8000))
RETURNS @CrackRow table
(
INROWS varchar(1000)
)
as
BEGIN
insert @CrackRow
Select NullIf(SubString(@Delim + @Phrase2Crack + @Delim , IDNos ,
CharIndex(@Delim , @Delim + @Phrase2Crack + @Delim , IDNos) - IDNos) , '') AS INROW
FROM IDNos
WHERE IDNos <= Len(@Delim + @Phrase2Crack + @Delim) AND
SubString(@Delim + @Phrase2Crack + @Delim , IDNos - 1, 1) = @Delim
AND CharIndex(@Delim , @Delim + @Phrase2Crack + @Delim , IDNos) - IDNos > 0
return
END
GO
Select * from TableName BI Inner Join Dbo.CrackInRows(' ',@FundName) FN On BI.FundName like '%' + FN.InRows+ '%' OR FC.Name like '%' + FN.InRows+ '%'



Chirag
Go to Top of Page

shay1975
Starting Member

2 Posts

Posted - 2006-08-23 : 02:04:37
Generates the following error..what is the IDNos table?

Server: Msg 208, Level 16, State 1, Procedure CrackInRows, Line 15
Invalid object name 'IDNos'.
Go to Top of Page
   

- Advertisement -