Friday, March 9, 2012

Help w/a SQL Query

Ok here's the deal. I'm not very good w/SQL so if I can get assistance with the exact commands it'd be greatly appreciated.

I want to add some conditions to copying items from one column into another (all in the same table)

I'll go head and give the field names too.

tblProduct is the table name
PartNumber and SearchTerm are the columns I'll be dealing with

I want to take everything that's in PartNumber and copy it into SearchTerm, but here are the conditions i need to set
Ignore Hyphens, so if I copy "a-b" it should come out as "ab"
&
All spaces should be converted to commas, so "a b" should be "a, b"
& i want to keep what's already in SearchTerm as is

I know it might be a lot to ask for but any help would be greatly appreciated.
Thank you.you would need to write a cursor or a set based query..something like :


DECLARE @.pnum varchar(50), @.sterm varchar(50), @.newpnum varchar(100)
DECLARE rs CURSOR
LOCAL
FORWARD_ONLY
OPTIMISTIC
TYPE_WARNING
FOR SELECT [id],PartNumber, SearchTerm FROM tblProduct
OPEN rs
fetch next from rs into @.id,@.pnum, @.sterm
WHILE ( @.@.FETCH_STATUS = 0 )
begin
SET @.newpnum = @.pnum
SET @.newpnum = REPLACE (@.newpnum, '-','') -- Ignoring the hyphons
SET @.newpnum = REPLACE (@.newpnum, ' ',',') -- Replacing spaces with comma's
SET @.newpnum = ISNULL(@.sterm,'') + @.newpnum
UPDATE tblProduct SET SearchTerm = @.newpnum WHERE CURRENT OF rs

FETCH NEXT FROM rs INTO @.id,@.pnum, @.sterm
END

CLOSE rs
DEALLOCATE rs

usually cursors are a performance hit but for one time operations like these I think its ok..you can use set based operations.with the same logic .its up to you

hth|||Thank you. I won't have a chance to try it out today but tomorrow I'll post back with my results.|||Worked like a dream. Thanks. :}

No comments:

Post a Comment