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)
 Multiple Updates w/o having to use Dynamic SQL

Author  Topic 

danielhai
Yak Posting Veteran

50 Posts

Posted - 2002-09-18 : 15:24:40

just wanted to share a little something that i found useful:

I found myself using Dynamic SQL a lot to do updates on specific rows, like passing in a variable @UpdateIDs='12,534,23,632' to update those specific IDs. I wrote a function that doesn't require using Dynamic SQL.

Instead of:

exec('update table set column = 1 where ID in (' + @UpdateIDs + ')')

I am now using:

update table
set column = 1
where ID in (SELECT ID from fn_GetIDsFromString(@UpdateIDs))


here's the function (and let me know if there's a better way to do it):



CREATE FUNCTION fn_GetIDsFromString (@String varchar(8000))
RETURNS @Return Table (ID int)
AS
BEGIN

declare @Current smallint,
@TempString varchar(20)

set @Current = 1

while (CHARINDEX(',',@String,@Current) > 0)
begin
set @tempstring = CHARINDEX(',',@String,@Current) - @Current

if @tempstring <> 0
begin
insert into @Return (ID) values (substring(@String,@Current, cast(@tempstring as int)) )
end

set @Current = CHARINDEX(',',@String,@Current) + 1
end

if substring(@String,@Current, len(@String)) <> 0
insert into @Return (ID) values (substring(@String,@Current, len(@String)) )

return
END


robvolk
Most Valuable Yak

15732 Posts

Posted - 2002-09-18 : 15:47:18
Yes, that's a good way to do it.

There are similar posts of your function in the SQL Team Script Library:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=14185
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=18378

And the other CSV articles we have:

http://www.sqlteam.com/SearchResults.asp?SearchTerms=csv
http://accesshelp.net/content/Report.asp?REPORT=4&PARAM_ID=46

Some of those will also work with SQL 7.0 and earlier, which don't have user-defined functions.

Go to Top of Page

ValterBorges
Master Smack Fu Yak Hacker

1429 Posts

Posted - 2002-09-18 : 18:11:13
Looks like a lot of extra code and a big trade off on maintainability.
Is there a big performance difference?



Go to Top of Page
   

- Advertisement -