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
 SQL Server Development (2000)
 Looping Through An Array To Create A Query

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-02-14 : 11:01:49
Jason writes "My goal is to pass a comma delimited list of words into a stored procedure, or simply a phrase with spaces in it, which I'll convert into an array. Then I'd like to create dynamic SQL within the stored procedure which would result in the following SQL statements (An example phrase is supplied)

'how are you' or 'how','are','you' is passed in to create:

SELECT phrase_id, '''' + Replace(Replace(p.phrase,',',''), ' ', ''',''') + '''' AS text
INTO #reply_temp
FROM phrase AS p
WHERE phrase LIKE '%how%'
OR phrase LIKE '%are%'
OR phrase LIKE '%you%'

SELECT reply_id,
CASE WHEN CHARINDEX('''how''',text) > 0 THEN 1 ELSE 0 END +
CASE WHEN CHARINDEX('''are''',text) > 0 THEN 1 ELSE 0 END +
CASE WHEN CHARINDEX('''you''',text) > 0 THEN 1 ELSE 0 END
AS word_count
FROM #reply_temp AS t, phrase AS p, phrases AS r
WHERE t.phrase_id = p.phrase_id AND p.phrase_id = r.phrase_id
ORDER BY word_count DESC, phrase_count DESC, p.phrase_id DESC, reply_count DESC, reply_id DESC


Just as a briefing, this stored procedure counts how many words in the phrase in the database match the supplied phrase. There may be a better way to do this, but for now, I'd like to learn more about building dynamic SQL using looping."

robvolk
Most Valuable Yak

15732 Posts

Posted - 2002-02-14 : 11:08:37
Merkin is your hero! Read these articles:

http://www.sqlteam.com/item.asp?ItemID=4599
http://www.sqlteam.com/item.asp?ItemID=4619

Garth has a great article on building CSV values, you can modify it to build SQL statements:

http://www.sqlteam.com/item.asp?ItemID=2368

And yes, Merkin has another way of searching for keywords!

http://www.sqlteam.com/item.asp?ItemID=5857

Go to Top of Page
   

- Advertisement -