Solved

Select the values from the first column in all tables in my database

Posted on 2009-05-19
10
231 Views
Last Modified: 2012-06-21
Hi,

I have a database with a number of tables, I want to return the values of the first column in each table.

To illustrate, if there are, say, 3 tables in the database MyDB called Table1, Table2, Table3 with columns as follows:

Table1 has columns LastName, FirstName, Title
Table2 has columns Street, City, Country
Table3 has columns Age, Ethnicity, Gender, AccommodationType

Then I want the equivalent of doing:

Select LastName from Table1
Select Street from Table2
Select Age from Table3
etc.

Of course, in the real database there are about fifty tables and each has its own ideosyncrasies and column names are different in each and of differing types. Can I automate this using schema objects like 'Column_Name' etc in a loop of some sort for each table in the DB?

Thanks
Iain
0
Comment
Question by:iaing1000
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
10 Comments
 
LVL 60

Expert Comment

by:chapmandew
ID: 24421187
you can run this query to get them..

select column_name from information_schema.columns
where table_name in('table1', 'table2', 'table3')
and ordinal_position = 1
0
 
LVL 57

Expert Comment

by:Raja Jegan R
ID: 24421272
Use the query below as the Select query for your cursor and execute the statement for each and every values:

Hope this helps
SELECT 'SELECT ' + CO.COLUMN_NAME + ' FROM ' + TA.TABLE_SCHEMA + '.' + TA.TABLE_NAME + ';'
FROM INFORMATION_SCHEMA.TABLES TA, INFORMATION_SCHEMA.COLUMNS CO
WHERE TA.TABLE_NAME = CO.TABLE_NAME
AND TA.TABLE_SCHEMA = CO.TABLE_SCHEMA
AND CO.ORDINAL_POSITION = 1

Open in new window

0
 

Author Comment

by:iaing1000
ID: 24421276
Hi,

Thanks for the fast response.

This only returns the actual names of the columns themselves. If you can imagine the result of the select staements I've used to illustrate the question, that is what I'm after.

Also, I won't have time to explicitly outline the names of the tables as you've outlined, since there will be a lot of them. Possibly increasing from 50 to 900 ,so it all needs to be automated with no explicit reference to the tables or columns themselves

Thanks
Iain
0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
LVL 60

Expert Comment

by:chapmandew
ID: 24421319
so, you want something to select ALL records from the "first" column of all of your tables?
0
 

Author Comment

by:iaing1000
ID: 24421321
Hi rrjegan,

I'll have a look at this, it looks useful.

It seems to return the actual SELECT statements themselves though. I'm after the result of running each of these resultant SELECTS one after the other, I'm trying to find a way of re-jigging your SQL to do this because it must be close.

 The result I'm after will be the same as pasting this...

Select LastName from Table1
Select Street from Table2
Select Age from Table3
etc.

...into the New Query area and clicking Execute

Thanks
Iain


0
 

Author Comment

by:iaing1000
ID: 24421329
Hi chapmandew,

Yes that's exactly right,

Thanks for being so quick too,

Iain
0
 
LVL 60

Accepted Solution

by:
chapmandew earned 250 total points
ID: 24421346
declare @sql nvarchar(4000), @tablename nvarchar(255), @columnname nvarchar(255)

DECLARE  CursorTemplate CURSOR
FAST_FORWARD FOR       
      
select table_name, column_name from INFORMATION_SCHEMA.COLUMNS
where ordinal_position = 1

OPEN CursorTemplate

FETCH NEXT FROM CursorTemplate
INTO      @tablename, @columnname

WHILE (@@FETCH_STATUS = 0)
BEGIN
      set @sql = 'select ' + @columnname + ' from ' + @tablename
      exec sp_executesql @sql

      FETCH NEXT FROM CursorTemplate
      INTO      @tablename, @columnname

END

CLOSE CursorTemplate
DEALLOCATE CursorTemplate
0
 
LVL 57

Expert Comment

by:Raja Jegan R
ID: 24421352
Test this one out which works as you explained:

DECLARE @sql nvarchar(1000);
DECLARE select_cur CURSOR FOR 
SELECT 'SELECT ' + CO.COLUMN_NAME + ' FROM ' + TA.TABLE_SCHEMA + '.' + TA.TABLE_NAME + ';'
FROM INFORMATION_SCHEMA.TABLES TA, INFORMATION_SCHEMA.COLUMNS CO
WHERE TA.TABLE_NAME = CO.TABLE_NAME
AND TA.TABLE_SCHEMA = CO.TABLE_SCHEMA
AND CO.ORDINAL_POSITION = 1;
 
    OPEN select_cur;
 
    FETCH NEXT FROM select_cur
    INTO @sql;
 
    WHILE @@FETCH_STATUS = 0
       BEGIN
          EXEC sp_executesql @sql;
          
          FETCH NEXT FROM select_cur
          INTO @sql;
       END;
    CLOSE select_cur;
    DEALLOCATE select_cur;

Open in new window

0
 
LVL 57

Assisted Solution

by:Raja Jegan R
Raja Jegan R earned 250 total points
ID: 24421373
A small change in SELECT query:
DECLARE @sql nvarchar(1000);
DECLARE select_cur CURSOR FOR 
SELECT 'SELECT ' + CO.COLUMN_NAME + ' FROM ' + TA.TABLE_SCHEMA + '.' + TA.TABLE_NAME + ';'
FROM INFORMATION_SCHEMA.TABLES TA, INFORMATION_SCHEMA.COLUMNS CO
WHERE TA.TABLE_NAME = CO.TABLE_NAME
AND TA.TABLE_SCHEMA = CO.TABLE_SCHEMA
AND CO.ORDINAL_POSITION = 1
AND TA.TABLE_TYPE = 'BASE TABLE';
 
    OPEN select_cur;
 
    FETCH NEXT FROM select_cur
    INTO @sql;
 
    WHILE @@FETCH_STATUS = 0
       BEGIN
          EXEC sp_executesql @sql;
          
          FETCH NEXT FROM select_cur
          INTO @sql;
       END;
    CLOSE select_cur;
    DEALLOCATE select_cur;

Open in new window

0
 

Author Comment

by:iaing1000
ID: 24421488
Hi,

Those both worked perfectly!

Thank you both ever so much,

Points split in a minute or two,

Thanks
Iain
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question