Click here to Skip to main content
15,912,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
In my below sp after executing it..as EXEC sp_SplitVal

SQL
ALTER PROC sp_SplitVal
AS
DECLARE @Test VARCHAR(1000), @RecSet VARCHAR(500)
DECLARE @StartingPos INT,@RecPos INT
DECLARE @temptable TABLE(COMPLEXIONID INT)
SET @StartingPos= 1
SET @TEST='1,3,4,'
--SET @Test =(select cmp.complexion1 from customerexpectation cmp where cmp.customerid='4fe6559c-bc93-4d9c-bcb2-013fede7d969')
WHILE 
    @StartingPos<=LEN(@Test)
BEGIN
    SELECT @RecPos = CHARINDEX(',',@Test,@StartingPos)
    SET @RecSet=SUBSTRING(@Test,@StartingPos,@RecPos-@StartingPos)
    PRINT @RecSet
    BEGIN
        INSERT INTO @temptable VALUES(@RecSet)
        SELECT * FROM @temptable
        SELECT @StartingPos=@RecPos+1
    END
END


i am getting the results in a loop for three times..as
XML
COMPLEXIONID
     1
COMPLEXIONID
     1
     3
COMPLEXIONID
     1
     3
     4

but i need it as in a single recordset..
XML
COMPLEXIONID
     1
     3
     4

i dont want in a loop...how to achieve this...
Posted
Updated 20-Dec-12 22:48pm
v3

Hi Sahmed,
your Sql Query is Ok, you just need to use select Query outside loop

SQL
alter PROC sp_SplitVal
AS
BEGIN
DECLARE @Test VARCHAR(1000), @RecSet VARCHAR(500)
DECLARE @StartingPos INT,@RecPos INT
DECLARE @temptable TABLE(COMPLEXIONID INT)
SET @StartingPos= 1
SET @TEST='1,3,4,'
--SET @Test =(select cmp.complexion1 from customerexpectation cmp where cmp.customerid='4fe6559c-bc93-4d9c-bcb2-013fede7d969')
WHILE @StartingPos<=LEN(@Test)
BEGIN
SELECT @RecPos = CHARINDEX(',',@Test,@StartingPos)
SET @RecSet=SUBSTRING(@Test,@StartingPos,@RecPos-@StartingPos)
PRINT @RecSet
BEGIN
INSERT INTO @temptable VALUES(@RecSet)
SELECT @StartingPos=@RecPos+1
END
END
SELECT * FROM @temptable
end


Thanks!
Yogendra Dubey
 
Share this answer
 
You only have one set of data, your problem is that the select you use to get the data is in the loop, execute this:

SQL
DECLARE @Test VARCHAR(1000), @RecSet VARCHAR(500)
DECLARE @StartingPos INT,@RecPos INT
DECLARE @temptable TABLE(COMPLEXIONID INT)
SET @StartingPos= 1
SET @TEST='1,3,4,'
--SET @Test =(select cmp.complexion1 from customerexpectation cmp where cmp.customerid='4fe6559c-bc93-4d9c-bcb2-013fede7d969')
WHILE 
    @StartingPos<=LEN(@Test)
BEGIN
    SELECT @RecPos = CHARINDEX(',',@Test,@StartingPos)
    SET @RecSet=SUBSTRING(@Test,@StartingPos,@RecPos-@StartingPos)
    PRINT @RecSet
    BEGIN
        INSERT INTO @temptable VALUES(@RecSet)
        SELECT @StartingPos=@RecPos+1
    END
END
SELECT * FROM @temptable

I've moved the select to the last line.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900