从表的列中获取所有记录,并在sql server中以CSV格式导出到表的其他列 [英] Fetch all the record from a column of a table and export into other column of a table in CSV form in sql server

查看:48
本文介绍了从表的列中获取所有记录,并在sql server中以CSV格式导出到表的其他列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须根据以下要求创建Sproc ....



我有两张桌子:



TableA包含:ID(标识列主键)



TableB包含:RandomID(此列将存储随机排序后生成的ID表AID使用NEWID())



现在,我的要求是从TableA随机排序所有ID后,Id必须存储在TableB的RandomID列表示:如果我正在生成随机数,即



通过NewID()从TableA订单中选择ID



以上查询的输出为:3 2 4 5 2。 。 。 19



然后,如何将上述输出导出到其他列,即表格的RandomID以CSV格式?即TableB的RandomID列必须以的形式存储。


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


我必须使用游标来满足此要求,但是在声明CURSOR并根据我的要求使用之后如何将其导出到其他表,或者是他们的任何其他替代方案来实现这个目标因为游标性能问题??



请尽快赐教。



在此先感谢!!

解决方案

 声明  @ids   varchar  50 ), @qNameIdCSV   varchar (max)= ' ' 
声明 RandomCursor cursor for 选择 ID 来自 TableA order by NEWID()
open RandomCursor
fetch next RandomCursor 进入 @ ids
while @@ FETCH_STATUS = 0
begin
- print @ids
set @ qNameIdCSV = @ qNameIdCSV + ' ,' + @ ids
获取 RandomCursor 进入 @ ids
end
close RandomCursor
deallocate RandomCursor
set @ qNameIdCSV = SUBSTRING( @ qNameIdCSV 2 ,len( @ qNameIdCSV ) - 1)

打印 @ qNameIdCSV - 检查所需输出

insert 进入 tableA(RandomID) @ qNameIdCSV - 这将使用NEWID()将随机生成的ID保存到CSV格式的所需列中

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 !!

解决方案

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


这篇关于从表的列中获取所有记录,并在sql server中以CSV格式导出到表的其他列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆