I have the following SQL script. As you can see I manually set the @listingid value to 30653.
But this script should be executed for all records in the [listings] table where @listingid is assigned the value of the [listings].id column.
DECLARE @profname nvarchar(150)
DECLARE @furl nvarchar(250)
DECLARE @city nvarchar(250)
DECLARE @listingid int
set @listingid=30653
--select the top 1 professionname
SELECT TOP 1 @profname=REPLACE(LOWER(pn.title),' ','-'),@furl=l.friendlyurl,@city=REPLACE(REPLACE(LOWER(l.city),'''',''),' ','-') FROM healthprof_professionnames hpn
INNER JOIN professionname pn ON pn.id=hpn.professionnameid
INNER JOIN listings l on l.id=hpn.healthprofid
WHERE l.id=@listingid ORDER BY pn.title
--check if current friendlyurl already contains profession
IF NOT CHARINDEX(@profname,@furl)>0
SET @furl = @furl + '-' + @profname
IF NOT CHARINDEX(@city,@furl)>0
SET @furl = @furl + '-' + @city
SET @furl = @furl + '-3'
UPDATE listings set friendlyurl=@furl WHERE id=@listingid
You can use a cursor to loop over every row in a result set:
That being said, I agree with Tim’s comment above. Rewrite it to work in one set-based operation if at all possible. I think this will work, but I haven’t tested it: