Wednesday, March 7, 2012

Error in function argument

I have a table with over 11,000 records and I need to do a find and replace using SET and Where conditions. Basically I have one column in the table called RealAudioLink. It contains entries like: wkdy20070416-a.rm and wkdy20070416-b.rm and conv20070416.rm.

I need the select statement to find all wkdy entries and replace those characters with Weekday. I also need it to find all dashes and small a's and b's and replace with null or nothing. Then I need it to insert a capital letter A or B in the
wkdy20070416-a.rm filename so that when it's all said and done that entry would read:

WeekdayA20070416.rm
WeekdayB20070416.rm
Conversation20070416.rm

Here is the code I am working with. It needs help. I'm close but I'm not knowledgeable with using SET or with removing dashes and inserting capital letters all in the same select statement.

Code Snippet

UPDATE T_Programs_TestCopy
(SET RealAudioLink = REPLACE(RealAudioLink, '-a', '')
AND
(SET RealAudioLink = REPLACE(RealAudioLink, 'wkdy', 'WeekdayA')
WHERE (RealAudioLink LIKE 'wkdy%'))


I've never done anything like this before so I would be very appreciative of any assistance with the select statement. I am reading up on it but it would be great to get another perspective from a more experienced sql developer.

Thanks

Here is an example of creating a custom function to make the changes, and then using that function in updating the table.

Code Snippet


CREATE FUNCTION dbo.fnCleanMyData
( @.BadDataIn varchar(2000) )
RETURNS varchar(2000)
AS
BEGIN
SET @.BadDataIn =
CASE
WHEN patindex( '%-a.rm', @.BadDataIn ) > 0
THEN replace( replace( stuff( @.BadDataIn, 5, 1, 'A' ), 'wkdy', 'Weekday' ), '-a', '' )
WHEN patindex( '%-b.rm', @.BadDataIn ) > 0
THEN replace( replace( stuff( @.BadDataIn, 5, 1, 'B' ), 'wkdy', 'Weekday' ), '-b', '' )
WHEN patindex( 'conv%', @.BadDataIn ) > 0
THEN replace( @.BadDataIn, 'conv', 'Conversation' )
END
RETURN @.BadDataIn
END
GO


DECLARE @.MyTable table
( FileNames varchar(100) )


SET NOCOUNT ON


INSERT INTO @.MyTable VALUES ( 'wkdy20070416-a.rm' )
INSERT INTO @.MyTable VALUES ( 'wkdy20070416-b.rm' )
INSERT INTO @.MyTable VALUES ( 'conv20070416.rm' )


SELECT FileNames
FROM @.MyTable

FileNames
-
wkdy20070416-a.rm
wkdy20070416-b.rm
conv20070416.rm

UPDATE @.MyTable
SET FileNames = dbo.fnCleanMyData( FileNames )

SELECT FileNames
FROM @.MyTable

FileNames
--
WeekdayA0070416.rm
WeekdayB0070416.rm
Conversation20070416.rm

Change the function name to whatever you like, and I have used a table variable in this example. Use your own table and column names.

No comments:

Post a Comment