SQL How to list Columns in a Table as a Cursor Statement

社会主义新天地 提交于 2020-01-05 08:52:14

问题


below is the only method by which i have been able to pull the table names out of our database, replacing the top 1 for 2, 3, 4..... 499, 500.

The problem is that there isn't direct access to the database, the use of a third party program (for law firms) has to access the data and this gives limited scope as to what can be done, thus the usual methods of bringing back data won't generally work. Data seems to be returned using cursors based on the errors output when using "for xml auto".

select(
(select min(name) from 
(select top 1 name from sys.Tables order by name desc)
as ax) + ', ' + 
(select min(name) from 
(select top 2 name from sys.Tables order by name desc)
as ax)  + ', ' + 

)

now i wish to repeat this procedure to return the second, third, fourth column_name within a table. THe below could works to retrive the first column_name

SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = <table name>

but my attempts to repeat the first procedure fails; top 2, top 3 etc returned the same column_name.

Help would be great.

thanks.


回答1:


Try to embed the for xml auto query in another select statement

select (select table_name, column_name, ordinal_position, data_type
        from information_schema.columns
        where table_name = 'T'
        order by 1,3
        for xml auto)

Using this in a cursors works fine:

declare C cursor for
select (select table_name, column_name, ordinal_position, data_type
        from information_schema.columns
        where table_name = ''
        order by 1,3
        for xml auto)
open C
declare @L varchar(max)
fetch next from C into @L
close C
deallocate C
select @L



回答2:


This should bring you all the information you require (tested on SQL Server 2005)

select table_name, column_name, ordinal_position, data_type
from information_schema.columns
where table_name = ''
order by 1,3
for xml auto


来源:https://stackoverflow.com/questions/5881952/sql-how-to-list-columns-in-a-table-as-a-cursor-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!