locked
how to select data AND column name? RRS feed

  • Question

  • hey,

    anyone an idea how i can easily select dataname & column names with one select from a table?

    i know that i can get the column names from the sys-tables. select just data from a table should also not be the problem ;)

    just how to combine those things like:

    Table mytable
    Product Price Whatever AndMore
    AX543 55 asdf qwert

    output of select should be:
    ValueColumn1 NameColumn1 ValueColumn2 NameColumn2 ValueColumn3 NameColumn3 ValueColumn3 NameColumn3 

    like:
    AX543 Product 55 Price asdf Whatever qwert AndMore

    Thx a lot in advance!
    greets

    Monday, January 28, 2013 9:06 AM

Answers

  • This make the job.

    declare @tableName varchar(30) = 'YourTable'; 
    
    declare @columnNames table(name varchar(30));
    insert into @columnNames select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tableName 
      
    declare @dynamicCommand varchar(max) = 'select '
    declare @columnName varchar(30)
    
    declare  columnNames_cursor cursor
    FOR
    select name from @columnNames
    
    Open columnNames_cursor
    
    FETCH NEXT FROM columnNames_cursor into @columnName
    
    while @@fetch_status = 0
    Begin
    	--print @columnName + ' : ' 
    	set @dynamicCommand = @dynamicCommand + '''' + @columnName + ''' + '' '' + convert(nvarchar,' +  @columnName + '), '
    
    	FETCH NEXT FROM columnNames_cursor into @columnName
    End
    Close columnNames_cursor
    Deallocate columnNames_cursor
    
    -- remove last ', '
    set @dynamicCommand = Substring( @dynamicCommand, 0, len (@dynamicCommand))
    
    print @dynamicCommand
    
    set @dynamicCommand = @dynamicCommand + ' from ' + @tableName 
    
    EXEC ( @dynamicCommand)

    Sorry, but I do not yet figure out why you have to do this.

    If I have to do something like this (dynamic tables) I prefer make the work by code, firstly obtaining the columns from table schema (with SQL type and nullability) and then dynamically creating the query for the data. 

    Then, knowing "structure"  and data I can perform all kind of operation/formatting.

    If my example is good for you I ask you to test for NULL value, varchar + NULL return NULL, if I remember correctly. I think the IsNull function can solve this, in case.

    For the first purpose .Net have all included facility (GetSchema(@tableName)), but for COBOL I think at this:

    SELECT 
       ORDINAL_POSITION
      ,COLUMN_NAME
      ,DATA_TYPE
      ,CHARACTER_MAXIMUM_LENGTH
      ,IS_NULLABLE
      ,COLUMN_DEFAULT
    FROM   
      INFORMATION_SCHEMA.COLUMNS 
    WHERE   
      TABLE_NAME = @tableName 
    ORDER BY 
      ORDINAL_POSITION ASC; 


    [Added]
    My example returns [NameColumn1 ValueColumn1], [NameColumn2 ValueColumn2] ... 
    To obtain result in the reverse order order (as your example) [ValueColumn1 NameColumn1] ecc...
    use this (I confirm my previous doubt about NULL value with string concatenation) with IsNull applied:

    set @dynamicCommand = @dynamicCommand + 'convert(nvarchar, IsNull(' +  @columnName + ', ''''))' + ' + '' '' + ''' + @columnName + ''', ' 

    (those are ALL single quote)

    You can also substitute the final ', ' with ''' ''' to obtain a unique long string exactly as your example in first request, or add more to separate data columns from column name columns.


    Monday, January 28, 2013 11:21 AM

All replies

  • What 's wrong with plain  Seclect  Product  as col1val, 'Product' as col1name, ...  ?


    Serg

    Monday, January 28, 2013 9:10 AM
  • What would be the case for the below:

    Product Price Whatever AndMore
    AX543 55 asdf qwert

    asdasd 33 sdf sdfdsf

    I guess, you want to do some kind of formatting for front end. If this is the case, please do it in front. SQL Server is not meant for formatting. You have much more features in front end.


    Please use Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful.

    • Proposed as answer by Junaid_Hassan Monday, January 28, 2013 10:30 AM
    Monday, January 28, 2013 9:14 AM
  • What 's wrong with plain  Seclect  Product  as col1val, 'Product' as col1name, ...  ?


    Serg

    Well, i wanna keep my whole statement variable.

    ie: the whole statement will be generated and will be used for different tables, with different amount of columns and so on.
    as of this a fix string like 'Product' will kind of "destroy" this variability.

    i hope, that i explained my idea more or less understandable ;)

    greets
    Monday, January 28, 2013 9:15 AM
  • What would be the case for the below:

    Product Price Whatever AndMore
    AX543 55 asdf qwert

    asdasd 33 sdf sdfdsf

    I guess, you want to do some kind of formatting for front end. If this is the case, please do it in front. SQL Server is not meant for formatting. You have much more features in front end.


    Please use Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful.

    no, i wanna do smth different:
    like: 
    Columnnames: ProductValue, ProductOperator ProducType
    Values: "1234,4567",  "not in", "Car"

    Out of this information i am constructing a kind of where-clause
    the columnname itself identifies for which column (of another table) the rule is for.

    so out of this Values i will generate a where-clause like "WHERE ProductValue not in (1234,4567)

    with this statement i can select data out of ie a table named "mywarehouse" 

    greets 
    Monday, January 28, 2013 9:30 AM
  • Since SQL Server 2008 you can script out schema and data for  tables... (Right click in the database --Generate Script...)

    Best Regards,Uri Dimant SQL Server MVP, http://sqlblog.com/blogs/uri_dimant/

    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Blog: Large scale of database and data cleansing
    Remote DBA Services: Improves MS SQL Database Performance

    Monday, January 28, 2013 9:30 AM
    Answerer
  • Since SQL Server 2008 you can script out schema and data for  tables... (Right click in the database --Generate Script...)


    i know. also no problem to select all the sys-data out of sys.tables, sys.schemas, sys.columns,...

    just the combination of those 2 selects is my problem, as i don't know how to "join" those 2 informations
    Monday, January 28, 2013 9:33 AM
  • CREATE TABLE Orders (ordid INT, qty INT, price REAL)


    SELECT t.name,s.name FROM sys.tables t JOIN sys.columns s
    ON t.object_id=s.object_id
    WHERE t.name='Orders'


    DROP TABLE Orders

    Best Regards,Uri Dimant SQL Server MVP, http://sqlblog.com/blogs/uri_dimant/

    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Blog: Large scale of database and data cleansing
    Remote DBA Services: Improves MS SQL Database Performance

    Monday, January 28, 2013 10:20 AM
    Answerer
  • I think that you do not really have to do this kind of work.
    What is your case, your finality?
    (And when the result has more records, you want the names of columns repeated in everyone?)

    Monday, January 28, 2013 10:22 AM
  • CREATE TABLE Orders (ordid INT, qty INT, price REAL)


    SELECT t.name,s.name FROM sys.tables t JOIN sys.columns s
    ON t.object_id=s.object_id
    WHERE t.name='Orders'


    DROP TABLE Orders


    i know how to select from the sys-tables. 
    but still i need to combine it with the data from "mytable"

    Monday, January 28, 2013 10:44 AM
  • I think that you do not really have to do this kind of work.
    What is your case, your finality?
    (And when the result has more records, you want the names of columns repeated in everyone?)

    mytable -> should include identification rules. this rule table should be very variable. amount of columns and also on which fields those columns point.
    i.e. rule definied in columns "
    ProductValue" and  "ProductOperator" kind of "point" on a field called "Product"

    "
    I think that you do not really have to do this kind of work."
    it is my work ;) i designed such a solution on Cobol&DB2 - now i am designing a similar solution on SQL Server

    PS: i know Cobol&DB2 IS NOT SQL Server ;)

    Monday, January 28, 2013 10:44 AM
  • of course those "identificationrules" will be much more complex.
    one rule will include much more different values to check - not just productnumber like in my example.

    it will be a quite comlex identification. which will be maybe also changed in future. due to this i wanna keep it variable too. 
    also with a high variability i am able to use this "solution" for different projects too

    Monday, January 28, 2013 10:51 AM
  • Why do you need that? Looks pretty odd.

    CREATE TABLE Orders (ordid INT, qty INT, price INT)

    INSERT INTO Orders VALUES (100,5,80)

    WITH cte
    AS
    (
    SELECT 'Orders' AS tblname, 'ordid'colname,ordid as colvalue FROM Orders
    UNION ALL
    SELECT 'Orders' AS tblname,'qty'colname,qty as colvalue FROM Orders
    UNION ALL
    SELECT 'Orders' AS tblname,'price'colname,price as colvalue FROM Orders
    ) SELECT DISTINCT tblname,s.name,colvalue FROM cte JOIN sys.tables t ON 
      t.name=cte.tblname   JOIN sys.columns s
    ON S.NAME=CTE.colname


    Best Regards,Uri Dimant SQL Server MVP, http://sqlblog.com/blogs/uri_dimant/

    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Blog: Large scale of database and data cleansing
    Remote DBA Services: Improves MS SQL Database Performance

    Monday, January 28, 2013 10:52 AM
    Answerer
  • This make the job.

    declare @tableName varchar(30) = 'YourTable'; 
    
    declare @columnNames table(name varchar(30));
    insert into @columnNames select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tableName 
      
    declare @dynamicCommand varchar(max) = 'select '
    declare @columnName varchar(30)
    
    declare  columnNames_cursor cursor
    FOR
    select name from @columnNames
    
    Open columnNames_cursor
    
    FETCH NEXT FROM columnNames_cursor into @columnName
    
    while @@fetch_status = 0
    Begin
    	--print @columnName + ' : ' 
    	set @dynamicCommand = @dynamicCommand + '''' + @columnName + ''' + '' '' + convert(nvarchar,' +  @columnName + '), '
    
    	FETCH NEXT FROM columnNames_cursor into @columnName
    End
    Close columnNames_cursor
    Deallocate columnNames_cursor
    
    -- remove last ', '
    set @dynamicCommand = Substring( @dynamicCommand, 0, len (@dynamicCommand))
    
    print @dynamicCommand
    
    set @dynamicCommand = @dynamicCommand + ' from ' + @tableName 
    
    EXEC ( @dynamicCommand)

    Sorry, but I do not yet figure out why you have to do this.

    If I have to do something like this (dynamic tables) I prefer make the work by code, firstly obtaining the columns from table schema (with SQL type and nullability) and then dynamically creating the query for the data. 

    Then, knowing "structure"  and data I can perform all kind of operation/formatting.

    If my example is good for you I ask you to test for NULL value, varchar + NULL return NULL, if I remember correctly. I think the IsNull function can solve this, in case.

    For the first purpose .Net have all included facility (GetSchema(@tableName)), but for COBOL I think at this:

    SELECT 
       ORDINAL_POSITION
      ,COLUMN_NAME
      ,DATA_TYPE
      ,CHARACTER_MAXIMUM_LENGTH
      ,IS_NULLABLE
      ,COLUMN_DEFAULT
    FROM   
      INFORMATION_SCHEMA.COLUMNS 
    WHERE   
      TABLE_NAME = @tableName 
    ORDER BY 
      ORDINAL_POSITION ASC; 


    [Added]
    My example returns [NameColumn1 ValueColumn1], [NameColumn2 ValueColumn2] ... 
    To obtain result in the reverse order order (as your example) [ValueColumn1 NameColumn1] ecc...
    use this (I confirm my previous doubt about NULL value with string concatenation) with IsNull applied:

    set @dynamicCommand = @dynamicCommand + 'convert(nvarchar, IsNull(' +  @columnName + ', ''''))' + ' + '' '' + ''' + @columnName + ''', ' 

    (those are ALL single quote)

    You can also substitute the final ', ' with ''' ''' to obtain a unique long string exactly as your example in first request, or add more to separate data columns from column name columns.


    Monday, January 28, 2013 11:21 AM