?
Solved

Sql Server 2008 split & Insert to a table

Posted on 2012-08-29
5
Medium Priority
?
242 Views
Last Modified: 2013-01-04
Hi,

I have a variable called @employeeID which is coming as "#" separated & i want to insert them separately into a database table.

create #tempTable
(
empID INT
)

declare  @employeeID VARCHAR(4000)
SET @employeeID = '2001#3001#4001#3211#'

I want to split these ids by '#' & insert them to #tempTable.

Result
---------------
select * from #tempTable

empid
-------
2001
3001
4001
3211

Can i get a sample code for this.
0
Comment
Question by:r_pat72
5 Comments
 
LVL 25

Expert Comment

by:lwadwell
ID: 38348605
here is one way:
IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
	DROP TABLE #tempTable

create table #tempTable (
    empID INT
)

declare  @employeeID VARCHAR(4000)
SET @employeeID = '2001#3001#4001#3211#'

declare  @1emplID  VARCHAR(4000)

WHILE len(@employeeID) > 0
BEGIN
    SET @1emplID = CASE WHEN CHARINDEX('#',@employeeID) > 0 THEN SUBSTRING(@employeeID,1,CHARINDEX('#',@employeeID)-1)
                        ELSE @employeeID
                   END
    INSERT INTO #tempTable ( empID ) values ( @1emplID )
    SET @employeeID = RIGHT(@employeeID,LEN(@employeeID)-LEN(@1emplID)-1)
END

SELECT * FROM #tempTable

Open in new window

0
 
LVL 16

Expert Comment

by:DcpKing
ID: 38348636
create table #tempTable
(
empID INT
)

declare  @employeeID VARCHAR(4000)
SET @employeeID = '2001#3001#4001#3211#'
--	-----------------
declare	@intThisPos int, @intNextPos int, @intLength int
set @employeeID = lTrim(rTrim(@employeeID))
set @intLength = len(@employeeID)
set @intThisPos = 1
while 'True' = 'True'
begin
set @intNextPos = charindex('#', @employeeID, @intThisPos)
if @intNextPos = 0 break
insert into #temptable
	select substring(@employeeID, @intThisPos, 4)
set @intThisPos = @intNextPos + 1
end

select * from #tempTable

Open in new window

0
 
LVL 22

Expert Comment

by:Thomasian
ID: 38348759
You can use dynamic SQL. Just check for invalid characters to avoid sql injection.
IF PATINDEX('%[^0-9]%',REPLACE(@employeeID,'#','')) = 0 BEGIN
	SET @sql = 'INSERT INTO #tempTable SELECT ' + REPLACE(STUFF(@employeeID,LEN(@employeeID),1,''),'#',' UNION ALL SELECT ')
	exec (@sql)
END

Open in new window

0
 
LVL 25

Expert Comment

by:lwadwell
ID: 38348820
To save yourself the trouble ever again ... you could take the logic you choose to use and implement as a custom function and then do:
IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
	DROP TABLE #tempTable

create table #tempTable (
    empID INT
)

declare  @employeeID VARCHAR(4000)
SET @employeeID = '2001#3001#4001#3211#'

INSERT INTO #tempTable ( empID ) SELECT items FROM Splitfn(@employeeID,'#')

SELECT * FROM #tempTable

Open in new window

Example function definition:
CREATE FUNCTION Splitfn(@String varchar(8000), @Delimiter char(1))       
returns @temptable TABLE (items varchar(8000))       
as       
begin
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
    if len(@String)<1 or @String is null return       

    while @idx != 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(ltrim(rtrim(@slice)))       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
    return      
end

Open in new window

0
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 2000 total points
ID: 38349016
I have also my version of splitting a string into rows:
http://www.experts-exchange.com/Database/Miscellaneous/A_1536-delimited-list-as-parameter-what-are-the-options.html
along with the different usages :)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question