Register
Thursday, September 09, 2010
 
 DBAs And ProgrammersBlog
  
News! Minimize
   
 
 Print   
 
Misc Blog Stuff Minimize
   
 
 Print   
 
The Reluctant DBA Minimize
 
 
 
 Print   
 
Reluctant DBA Minimize
   
 
  
 
Reluctant DBA Minimize
   
 
  
 
The Reluctant DBA Minimize
 
Dec1

Written by:CarpDeus
12/1/2008 10:20 AM 

SQL Server is set based. Sometimes we get data that isn't. And, when that happens, we need to convert it. One way to do this is using a simple function like this one:

-- =============================================
-- Author:        Josef Finsel
-- Create date: 2008-12-1
-- Description:    Split delimited list into
--              generic single column rows
--                based on passed in delmiter
-- =============================================
ALTER FUNCTION [dbo].[Delimited2Rows]
(
    @DelimitedString nvarchar(max),
    @Delimiter char(1)
)
RETURNS
@HoldingTable TABLE (
    IDColumn bigint identity primary key,
    DataColumn nvarchar(1024) )
AS
BEGIN
    while charindex(@Delimiter,@DelimitedString)>1
     begin
      INSERT INTO @HoldingTable VALUES(ltrim(rtrim(substring(@DelimitedString,1, charindex(@Delimiter,@DelimitedString)-1))))
      set @DelimitedString = substring(@DelimitedString, charindex(@Delimiter,@DelimitedString)+1, len(@DelimitedString))
     end
    if len(@DelimitedString)>0
      INSERT INTO @HoldingTable values(rtrim(ltrim(@DelimitedString)))
    RETURN
END

-- SELECT * FROM dbo.Delimited2Rows('testing;another row;WHat about me?!?;',';')

Now, SQL Server isn't really good at string manipulation, so this isn't something I'd want in a heavily used stored procedure. But, for converting data, it's handy. It doesn't support correctly parsing quoted text, so SELECT * FROM dbo.Delimited2Rows('"I like to eat cows; however, they don''t like to be eaten by me."',';') will return two rows, one containing "I like to eat cows and one containing however, they don't like to be eaten by me." Again, it's not designed to be a full blown parser, just a short step toward making life easier sometimes.

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment  Cancel 
 
 
  
 
Privacy Statement | Terms Of Use Copyright 2001-2008 by ReluctantDBA.com