For application sake, the main goal here is that in my front-end I want to be able to pull the field data from a sql server table and store it in my own database. (The application creates data files from database values). But I want the metadata and the
Say I have table FOO defined as below:
create TABLE foo
( id INT NOT NULL
, col2 INT NOT NULL
, col3 VARCHAR(10) NULL
, col4 DATE NULL
, col5 DECIMAL(14,5) NULL
);
With data as defined:
INSERT INTO foo (id, col2, col3, col4, col5) VALUES
(1,1,NULL,NULL,NULL)
,(2,2,'2','2/2/2012',22.22)
,(3,3,'3','3/3/2013',333.333)
,(4,4,NULL,'4/4/2014',4444.4444)
,(5,5,'5',NULL,55555.55555)
,(6,6,'6','6/6/2016',NULL);
Assuming this can be applied to any table where I don't know the columns, I want the following returned:
column_name | value
----------------------------
id | 1
col2 | 1
col3 | 2
col4 | 2/2/2012
col5 | 22.22
So basically, I want to retrieve the column_name with the first non-null value for that column, but at this point I'll settle for a solution that will just return the first value even if it is null.
Now, I have a query to get all the metadata, but i'm not sure how to add another column to the query to also get the data for that column name. (simplified to just pull column_name as I'm also retrieving other metadata). Again, I have to do it dynamically and can't store it as a procedure.
SELECT
sc.name AS column_name
FROM
sys.columns sc
WHERE
sc.object_id = OBJECT_ID('FOO')
ORDER BY
sc.column_id
All of the answers I have seen have been non-dynamic with hardcoded column names, but I'm looking for an option where it will work across tables by just plugging in the table name. I'm not sure if it's possible or not. i.e. this solution