Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I've to create Sproc for below requirement....

I've got two table:

TableA Contains: ID (identity column primary key)

TableB contains: RandomID (This column will store ID that will be generated after randomly sorting Table A "ID" using NEWID() )

Now, my requirement is After random sorting of all "ID" from "TableA" that Id must be stored in the column "RandomID" of TableB It means : If I'm generating the Random No. i.e

"select ID from TableA order by NewID()"

Output of above query as: 3 2 4 5 2 . . . 19

then, how to export the above output into other column i.e "RandomID" of TableB in CSV form ?? i.e "RandomID column of TableB" must store in the form of

3,2,4,5....,,19

I've to use cursor for this requirement but how to export it to other table after declaring CURSOR and to use according to my requirement, or is their any other alternative to achieve this goal because of Cursor performance issue ??

Please, enlighten me soon.

Thanks In advance !!
Posted
Comments
Zoltán Zörgő 31-May-13 1:49am    
The id and it's random order is one thing - a simple insert into. But a the CSV form(at) makes no sense. One single value is itself in CSV format also.
Rabbil 31-May-13 2:33am    
I've to insert one Id generated from one table into other column of a table which would be in CSV format
Zoltán Zörgő 31-May-13 2:43am    
I got your words, but not their meaning: there is no such thing in SQL Server as table in csv format. You will need to export your table in that format by the means of your application.
Rabbil 31-May-13 3:12am    
I mean, if the random Id generated from NEWID() is 3.2.5.4.1....n times then this output must be stored into other column of a table in the form of 3,2,5,4,1,,,,n times (it must be in a single column from the output of 1st column)
Hope u got, what i meant ??

1 solution

SQL
declare @ids varchar(50),@qNameIdCSV varchar(max)=''
 declare RandomCursor cursor for select ID from TableA order by NEWID()
        open RandomCursor 
        fetch next from RandomCursor into @ids
        while @@FETCH_STATUS=0
        begin
        --print @ids
        set @qNameIdCSV=@qNameIdCSV+','+@ids
        fetch next from RandomCursor into @ids
        end
        close RandomCursor 
        deallocate RandomCursor 
        set @qNameIdCSV=SUBSTRING(@qNameIdCSV,2,len(@qNameIdCSV)-1) 

print @qNameIdCSV --check the required output
or 
insert into tableA (RandomID) values (@qNameIdCSV) -- this will save the random generated ID using NEWID() into the required column in CSV form
 
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