开发者

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

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 开发者_StackOverflow3 etc returned the same column_name.

Help would be great.

thanks.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜