How to merge three columns values to single row values in sql server 2008

Hi Frds.....
I have three quantity in my table.
Quantity1,quantity2,quantity3
this three quantity have different values
ex:
quantity1 = 1000,quantity2=2000,quantity3=3000
the three column combine 2 display in single row values. this values display in one by one.
ex: quantity
     1000
     2000
     3000

You will need to use the UNPIVOT operator:
DECLARE @example TABLE
Id int NOT NULL IDENTITY(1,1),
Quantity1 int,
Quantity2 int,
Quantity3 int
INSERT INTO @example VALUES (1000, 2000, 3000), (4000, 5000, 6000);
SELECT * FROM @example;
SELECT Id, Quantity, QuantityType
FROM @example
UNPIVOT
Quantity FOR QuantityType IN (Quantity1, Quantity2, Quantity3)
) AS u;
Output:
(2 row(s) affected)
Id Quantity1 Quantity2 Quantity3
1 1000 2000 3000
2 4000 5000 6000
(2 row(s) affected)
Id Quantity QuantityType
1 1000 Quantity1
1 2000 Quantity2
1 3000 Quantity3
2 4000 Quantity1
2 5000 Quantity2
2 6000 Quantity3
(6 row(s) affected)

Similar Messages

  • Connecting JDBC Single Row Query to SQL Server 2008

    Hello,
    I am new to workbench and am having a very dificult time accessing a database and running a query on it. I have searched a lot on the internet for suggestion on how to accomplish this but nothing has worked. The LiveCycle was intaled on the same server that the SQL Server is sintalled, and was installed by an administrator who is no longer at our company. So I am trying to have the user input an account number into the form I have created, then take that account number and use an xpath expression to query the database and extract the information for that account. Could anyone please help me set this up.
    I Changed my my-db2-ds.xml to the following:
    <local-tx-datasource>
      <jndi-name>SQLDB_IMACS</jndi-name>
      <connection-url>jdbc:sqlserver://CBS-SQL-001;databaseName=DB_IMACS;integratedSecurity=tru e;</connection-url>
      <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
    </local-tx-datasource>
    and I get the following error message:
    Exception: Could not create connection; - nested throwable: (org.jboss.resource.JBossResourceException: Failed to register driver for: com.microsoft.sqlserver.jdbc.SQLServerDriver; - nested throwable: (java.lang.ClassNotFoundException: No ClassLoaders found for: com.microsoft.sqlserver.jdbc.SQLServerDriver)); - nested throwable: (org.jboss.resource.JBossResourceException: Could not create connection; - nested throwable: (org.jboss.resource.JBossResourceException: Failed to register driver for: com.microsoft.sqlserver.jdbc.SQLServerDriver; - nested throwable: (java.lang.ClassNotFoundException: No ClassLoaders found for: com.microsoft.sqlserver.jdbc.SQLServerDriver)))
    I have the following file sqljdbc.jar in my Adobe LiveCycle ES2\jboss\server\lc_turnkey\lib\ folder.
    If you could please let me know what I can do to connect that would be very useful.
    Thanks,
    sgarciacode19

    You will need to use the UNPIVOT operator:
    DECLARE @example TABLE
    Id int NOT NULL IDENTITY(1,1),
    Quantity1 int,
    Quantity2 int,
    Quantity3 int
    INSERT INTO @example VALUES (1000, 2000, 3000), (4000, 5000, 6000);
    SELECT * FROM @example;
    SELECT Id, Quantity, QuantityType
    FROM @example
    UNPIVOT
    Quantity FOR QuantityType IN (Quantity1, Quantity2, Quantity3)
    ) AS u;
    Output:
    (2 row(s) affected)
    Id Quantity1 Quantity2 Quantity3
    1 1000 2000 3000
    2 4000 5000 6000
    (2 row(s) affected)
    Id Quantity QuantityType
    1 1000 Quantity1
    1 2000 Quantity2
    1 3000 Quantity3
    2 4000 Quantity1
    2 5000 Quantity2
    2 6000 Quantity3
    (6 row(s) affected)

  • How to hide not all but a specific database on a SQL Server 2008 R2 instance?

    Hello everyone,
          I need help from all the SQL Server database security experts out there. Any solution/help or work-around will be really appreciated. Here is the scenario; our client is using our application which is a windows forms application
    having in backend as a database under SQL Server 2008 R2 instance. We have successfully installed the SQL Server software with mixed mode authentication on client side, our application is running smoothly and everything is working fine. Our database on which
    application is running is quite intuitive, in the sense, all employees information is stored in EmployeeMaster and all departments information is stored in DepartmentMaster and so on. It consists of more than 500 such tables, stored-procedures and views. We
    have encrypted stored-procedures and views, problem is only with tables.
    We don't want table structure to be visible to anybody in SSMS (or tables must be hidden from all the users) but at the same time the tables should be accessible from the application. And we don't want to go with the option of encrypting
    the tables data and changing the names of all the tables to T001,T002..etc. as that is not feasible. And one last thing, we cannot restrict 'sa' login's password, it has to be shared with the client.
    Regards,
    Sumit R. Santani

    Also, will you please enlighten me more on what you said as "couple of choices" if I want to lock out plain users only?
    Assuming that you are selling a solution to a client, it's more an issue for your client's IT department, that do want their users to connect with Excel or SSMS.
    Anyway, I have a brief overview here:
    http://www.sommarskog.se/grantperm.html#Othermethods
    Again my question on that is how much reliable will be that license agreement?
    That depends on the lawyer you engage to write the license agreement.
    How would I come to know what they are doing with our database?
    Trust. Trust is extremely important. It is very difficult to make business if you don't trust people.
    That said, there are basically two reasons you want to hide the application from the client. One is protecting intellectual property. To this end, I know of nothing else than trust. And maybe after all, your application is not so fantastic that it is worth
    stealing anyway.
    The other reason is that you don't want the client to change it, and then open a free support case when he has messed up. To this end there are some technical approaches you can take to detect such tampering. For instance, you can sign all stored procedures
    with certificates using ADD SIGNATURE WITH SIGNED BLOB, and then ship only the public key of the certificate. This permits SQL Server to verify the signature, but the client cannot change the signature and sign it with that certificate, because the private
    key is not available to them.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Set out of range value to a time datatype in sql server 2008

    Hi,
    I have a variable set to time datatype in SQL server 2008. I need to set a value more than 24 hrs to that. Is there any way? I get an error like Conversion failed when converting date and/or time from character string. .Below is my scenario
    declare @QuietBeginTime time
    SET @QuietBeginTime  = (SELECT value FROM #RCQD where id=8)
    ---------This has a value like '24:45'
    Print @QuietBeginTime
    Please help me.
    Deepa

    declare @QuietBeginTime time
    SET @QuietBeginTime  = (SELECT value FROM #RCQD where id=8)
    ---------This has a value like '24:45'
    Print @QuietBeginTime
    Above is my scenario. Your example is fine, But main thing is i want to set a value to a variable, That
    i am unable to do
    Deepa

  • How to maintain previous and record count in audit table in SQL Server 2008 r2?

    Hi Experts ,
     Situation :
    in our database we are having few of stored procedures which will drop and recreates the tables and it is scheduled on weekly basis. when this job will run all the stored procedures will drop all the tables and recreate. Now we need to create one table which
    will maintain history of the records.
    my table structure is listed below
    TableName CurrentReocrdCount CurrentExecutionDate PreviousReordCount PreviousExurtiondate
    TEST         1000                   2014-03-30            NULL        NULL
    Test         1500                   2014-04-10            1000      2014-03-30
    Test         2000                   2014-04-11            1500      2014-04-10 
    How do i achive this . 
    franklinsentil

    You need to create audit tables for these. The table will be populated by COUNT value inside stored procedure. Each time it clears the main table and fills new data and also logs count details to audit tables. You can use COUNT(*)  to get count value
    and GETDATE function to get current execution value.
    So proc will look like
    CREATE PROC procname
    @param....
    AS
    --step to drop existing table
    IF OBJECT_ID('tablename') IS NOT NULL
    DROP TABLE <table name>
    --step to fill new table
    SELECT ...
    INTO TableName
    FROM
    --Audit table fill step
    INSERT AuditTable (TableName,CurrentRecordCount,CurrentExecdate,PrevRecordCount,PrevExecDate)
    SELECT TOP 1 'TableName',(SELECT COUNT(*) FROM tableName),GETDATE(),CurrentRecordCount,CurrentExecDate
    FROM AuditTable
    ORDER BY CurrentExecDate DESC
    UNION ALL
    SELECT 'TableName',(SELECT COUNT(*) FROM tableName),NULL,NULL
    WHERE NOT EXISTS (SELECT 1 FROM AuditTable)
    GO
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How to change the name of the named instance in MS sql server 2008 R2

    Hi Gurus
    I have installed a  SAP ECC 6 ehp4 on MS sql server 2008 R2 with MS windows 2008 R2 OS.  While installing sql server i have selected  named instance from  window(default instance, named instance).   and given name  QAS.
    and installed ECC6 ehp4 ABAP engine successfully. now i want to change the name of mssql server's named instance name to DEV.
    kindly let me know
    which one is the best and easy solution
    1. changing the name of named istance at database level and SAP.
    2. or uninstalling  the existing SAP, DB and start from scratch.
    if first is the best, what would be the steps
    Thanks in advance
    balaji

    Hello,
    Please check this note:
    11692 - Renaming the system ID
    regards,
    John Feely

  • How can i get all these values in single row with comma separated?

    I have a table "abxx" with column "absg" Number(3)
    which is having following rows
    absg
    1
    3
    56
    232
    43
    436
    23
    677
    545
    367
    xxxxxx No of rows
    How can i get all these values in single row with comma separated?
    Like
    output_absg
    1,3,56,232,43,436,23,677,545,367,..,..,...............
    Can you send the query Plz!

    These all will do the same
    create or replace type string_agg_type as object
    2 (
    3 total varchar2(4000),
    4
    5 static function
    6 ODCIAggregateInitialize(sctx IN OUT string_agg_type )
    7 return number,
    8
    9 member function
    10 ODCIAggregateIterate(self IN OUT string_agg_type ,
    11 value IN varchar2 )
    12 return number,
    13
    14 member function
    15 ODCIAggregateTerminate(self IN string_agg_type,
    16 returnValue OUT varchar2,
    17 flags IN number)
    18 return number,
    19
    20 member function
    21 ODCIAggregateMerge(self IN OUT string_agg_type,
    22 ctx2 IN string_agg_type)
    23 return number
    24 );
    25 /
    create or replace type body string_agg_type
    2 is
    3
    4 static function ODCIAggregateInitialize(sctx IN OUT string_agg_type)
    5 return number
    6 is
    7 begin
    8 sctx := string_agg_type( null );
    9 return ODCIConst.Success;
    10 end;
    11
    12 member function ODCIAggregateIterate(self IN OUT string_agg_type,
    13 value IN varchar2 )
    14 return number
    15 is
    16 begin
    17 self.total := self.total || ',' || value;
    18 return ODCIConst.Success;
    19 end;
    20
    21 member function ODCIAggregateTerminate(self IN string_agg_type,
    22 returnValue OUT varchar2,
    23 flags IN number)
    24 return number
    25 is
    26 begin
    27 returnValue := ltrim(self.total,',');
    28 return ODCIConst.Success;
    29 end;
    30
    31 member function ODCIAggregateMerge(self IN OUT string_agg_type,
    32 ctx2 IN string_agg_type)
    33 return number
    34 is
    35 begin
    36 self.total := self.total || ctx2.total;
    37 return ODCIConst.Success;
    38 end;
    39
    40
    41 end;
    42 /
    Type body created.
    [email protected]>
    [email protected]> CREATE or replace
    2 FUNCTION stragg(input varchar2 )
    3 RETURN varchar2
    4 PARALLEL_ENABLE AGGREGATE USING string_agg_type;
    5 /
    CREATE OR REPLACE FUNCTION get_employees (p_deptno in emp.deptno%TYPE)
    RETURN VARCHAR2
    IS
    l_text VARCHAR2(32767) := NULL;
    BEGIN
    FOR cur_rec IN (SELECT ename FROM emp WHERE deptno = p_deptno) LOOP
    l_text := l_text || ',' || cur_rec.ename;
    END LOOP;
    RETURN LTRIM(l_text, ',');
    END;
    SHOW ERRORS
    The function can then be incorporated into a query as follows.
    COLUMN employees FORMAT A50
    SELECT deptno,
    get_employees(deptno) AS employees
    FROM emp
    GROUP by deptno;
    ###########################################3
    SELECT SUBSTR(STR,2) FROM
    (SELECT SYS_CONNECT_BY_PATH(n,',')
    STR ,LENGTH(SYS_CONNECT_BY_PATH(n,',')) LN
    FROM
    SELECT N,rownum rn from t )
    CONNECT BY rn = PRIOR RN+1
    ORDER BY LN desc )
    WHERE ROWNUM=1
    declare
    str varchar2(32767);
    begin
    for i in (select sal from emp) loop
    str:= str || i.sal ||',' ;
    end loop;
    dbms_output.put_line(str);
    end;
    COLUMN employees FORMAT A50
    SELECT e.deptno,
    get_employees(e.deptno) AS employees
    FROM (SELECT DISTINCT deptno
    FROM emp) e;
    DEPTNO EMPLOYEES
    10 CLARK,KING,MILLER
    20 SMITH,JONES,SCOTT,ADAMS,FORD
    30 ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES
    CREATE OR REPLACE FUNCTION concatenate_list (p_cursor IN SYS_REFCURSOR)
    RETURN VARCHAR2
    IS
    l_return VARCHAR2(32767);
    l_temp VARCHAR2(32767);
    BEGIN
    LOOP
    FETCH p_cursor
    INTO l_temp;
    EXIT WHEN p_cursor%NOTFOUND;
    l_return := l_return || ',' || l_temp;
    END LOOP;
    RETURN LTRIM(l_return, ',');
    END;
    COLUMN employees FORMAT A50
    SELECT e1.deptno,
    concatenate_list(CURSOR(SELECT e2.ename FROM emp e2 WHERE e2.deptno = e1.deptno)) employees
    FROM emp e1
    GROUP BY e1.deptno;
    DEPTNO EMPLOYEES
    10 CLARK,KING,MILLER
    20 SMITH,JONES,SCOTT,ADAMS,FORD
    30 ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES
    CREATE OR REPLACE TYPE t_string_agg AS OBJECT
    g_string VARCHAR2(32767),
    STATIC FUNCTION ODCIAggregateInitialize(sctx IN OUT t_string_agg)
    RETURN NUMBER,
    MEMBER FUNCTION ODCIAggregateIterate(self IN OUT t_string_agg,
    value IN VARCHAR2 )
    RETURN NUMBER,
    MEMBER FUNCTION ODCIAggregateTerminate(self IN t_string_agg,
    returnValue OUT VARCHAR2,
    flags IN NUMBER)
    RETURN NUMBER,
    MEMBER FUNCTION ODCIAggregateMerge(self IN OUT t_string_agg,
    ctx2 IN t_string_agg)
    RETURN NUMBER
    SHOW ERRORS
    CREATE OR REPLACE TYPE BODY t_string_agg IS
    STATIC FUNCTION ODCIAggregateInitialize(sctx IN OUT t_string_agg)
    RETURN NUMBER IS
    BEGIN
    sctx := t_string_agg(NULL);
    RETURN ODCIConst.Success;
    END;
    MEMBER FUNCTION ODCIAggregateIterate(self IN OUT t_string_agg,
    value IN VARCHAR2 )
    RETURN NUMBER IS
    BEGIN
    SELF.g_string := self.g_string || ',' || value;
    RETURN ODCIConst.Success;
    END;
    MEMBER FUNCTION ODCIAggregateTerminate(self IN t_string_agg,
    returnValue OUT VARCHAR2,
    flags IN NUMBER)
    RETURN NUMBER IS
    BEGIN
    returnValue := RTRIM(LTRIM(SELF.g_string, ','), ',');
    RETURN ODCIConst.Success;
    END;
    MEMBER FUNCTION ODCIAggregateMerge(self IN OUT t_string_agg,
    ctx2 IN t_string_agg)
    RETURN NUMBER IS
    BEGIN
    SELF.g_string := SELF.g_string || ',' || ctx2.g_string;
    RETURN ODCIConst.Success;
    END;
    END;
    SHOW ERRORS
    CREATE OR REPLACE FUNCTION string_agg (p_input VARCHAR2)
    RETURN VARCHAR2
    PARALLEL_ENABLE AGGREGATE USING t_string_agg;
    /

  • Radio button in three column in a single selection-screen

    Hi,
    I am trying to create radio buttons with three column within a single selection-screen.
    I.e.
    Column 1:
    radio1
    Column2:
    radio2
    radio3
    column3:
    radio4
    radio5
    radio6
    Also I wish to give three names(as headers) to each columns.Is is possible?If yes how?

    Hi,
    write as :
    SELECTION-SCREEN COMMENT /1(50) text-001.
    PARAMETERS: r1 RADIOBUTTON GROUP rad1.
    SELECTION-SCREEN COMMENT /1(30) text-002.
    PARAMETERS: r2 RADIOBUTTON GROUP rad1,
                r3 RADIOBUTTON GROUP rad1.
    SELECTION-SCREEN COMMENT /1(30) text-003.
    PARAMETERS: r4 RADIOBUTTON GROUP rad1,
                             r5 RADIOBUTTON GROUP rad1,
                             r6 RADIOBUTTON GROUP rad1.
    Regards,
    Srini.

  • How to bring all columns in a single/first page in report painter

    Hi Experts,
    There are 9 columns in a report painter which includes 1 lead column.
    7 columns comes in a first page including lead column and rest 2 columns goes to second page. This report is copied from another report where all columns comes in a first page only. if the original report comes in one page then why not the new report.
    Please suggest how to bring all columns in a single/first page in the new report.
    Please revert if I'm confused anywhere.
    Thanks in advance
    Arabinda

    Hi Rajneesh,
    Thanx for the quick reply. When I change the column width to 10 it comes in one page. But the requirement is to keep the column width to at least 12 or 14 and moreever the original report from where this report is copied having the same no of columns and the column width for original report is 14 and it comes in one page only.
    Do I need to do something more to achieve this. My question is how the original reports data comes in one page where as the current report having issue with same number of columns.
    Pls suggest.
    Thanx,
    Arabinda

  • How to aggregate a column based date column (for weekly single row)?

    How to aggregate a column based date column (for weekly single row)?

    Hi,
    Consider the below statement for daily bases which is ok
    SELECT ID, DATE, SUM(AMOUNT) FROM TABLE_NAME GROUP BY ID, DATE ORDER BY ID, DATE
    The same like the above statement, I want output on weekly, fortnightly, and monthly bases, How to do this? Need your help...

  • SPGridView with filtering on Taxonomy Field Multivalue column( column with multiple values in single row)

    Hi
    I have SPGridView  control (fetching value from DB) with a column which is having multiple values
    in single row seperated by ";", whenever filter applied it show these values in single row but i want
    to dispaly these values separately in diff. rows when column filter is applied.
    I have exactly same req. as mentioned in http://sadomovalex.blogspot.in/2011/03/spgridview-with-filtering-by-multiple.html
    but this solution didn't work for me.
    Please help/suggest.

    Hi Erland,
    Thank you very much for the answer. Sorry I had to be more accurate on my XML : This XML is in a SQL Server Table column. This table also has an id column. It will be great if you can answer specifically to this.
    <RootNode>
    <Node1>
    <Line_id_Node>1 </Line_id_Node>
    <A>
    <B>
    <D>Val1 </D>
    </B>
    <B>
    <D>Val2 </D>
    </B>
    <B>
    <D>Val3 </D>
    </B>
    </A>
    </Node1>
    <Node1>
    <Line_id_Node> 2 </Line_id_Node>
    <A>
    <B>
    <D>Val4 </D>
    </B>
    <B>
    <D>Val2 </D>
    </B>
    </A>
    </Node1>
    <Node1>
    <Line_id_Node> 3 </Line_id_Node>
    <A>
    <B>
    <D>Val5 </D>
    </B>
    </A>
    </Node1>
    </RootNode>
    Expected O/P:
    Line_id_Node                Column_D
    1                                                                    1                                           
    val1, val2, val3
    2                                                                    2                                               
    val4, val2
    3                                                                    3                                                  
    val5
    Nichesl

  • How to convert rows to columns in sql server 2008

    How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)

    Lookup the Pivot transformation. From BOL:
    The Pivot transformation makes a normalized data set into a less normalized
    but more compact version by pivoting the input data on a column value. For
    example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
    details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
    single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
    null values.
    When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
    The column is passed through unchanged to the output. Because many input rows
    can result only in one output row, the transformation copies only the first
    input value for the column.
    The column acts as the key or part of the key that identifies a set of
    records.
    The column defines the pivot. The values in this column are associated with
    columns in the pivoted dataset.
    The column contains values that are placed in the columns that the pivot
    creates.
    Paul

  • [Forum FAQ] How do I add an average line to series group on SQL Server Reporting Services column chart?

    Introduction
    In SQL Server Reporting Service (SSRS), you may need an average value on column chart.
    For the above chart, add an average score line to the chart, you can get which student’s score is larger than average score, and which student’s score is less than average score clearly. This document demonstrates how to add an average line to series groups
    on SSRS column chart.
    Solution
    To achieve this requirement, you can add another values to the chart, change the chart type to line chart. Set the value to average value of the series group and set the line to show only once by using expression. Please refer to the link below to see the
    detail steps.
    Click the chart to display the Chart Data pane.
    Add Score field to the Values area.
    Right-click the new inserted Score1 and select Change Chart Type. And then change chart type to line chart in the Select Chart Type window.
    Change the Category Group name to Subject. Here are the screenshot for you reference.
    Right-click the new inserted Score1 and select Series Properties.
    Click the expression button on the right of Value field textbox, type the expression below:
    =Avg(Fields!Score.Value,"Subject"))
    Click Visibility in the left pane, select “Show or hide based on an expression”, and type in the expression below:
    =IIF(Fields!Name.Value="Rancy",FALSE,TRUE)
    Name in the expression is one of the Students. Then only one line chart is be displayed by using this expression.
    Click Legend in the left pane, type Average_Score to the Custom legend text box.
    The report looks like below:
    Applies to
    Microsoft SQL Server 2005
    Microsoft SQL Server 2008
    Microsoft SQL Server 2008 R2
    Microsoft SQL Server 2012
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    Thanks,
    Is this a supported scenario, or does it use unsupported features?
    For example, can we call exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='b64ce7ec-d598-45cd-bbc2-ea202e0c129d'
    in a supported way?
    Thanks! Josh

  • Concatenate strings from a column into a single row

    I am trying to string values from a column into a single row. I need a list of students (one row per student) with their phone number and they could have more than one number. I found a function that should do what I need but the syntax is for SQL Server, not SQL*Plus. I've tried several variations but can not come up with the correct syntax.
    This is the SQL Server version:
    CREATE FUNCTION dbo.GetPhoneList(@StudentID int)
    RETURNS varchar(500) AS
    BEGIN
    DECLARE @StringList varchar(500)
    SELECT @StringList = COALESCE(@StringList + ‘, ‘, ”) + Telephone.PhoneNumber
    FROM Telephone t
    WHERE t.StudentID = @StudentID
    IF @StringList IS NULL
    SET @StringList = ‘No Phone’
    RETURN @StringList
    END
    SQL*Plus does not like the @ symbol, so I tried taking that out. I've put semi-colons where I think they should be, but I still get various error messages. Any suggestions?
    Thanks.

    Hi,
    What you want to do is called "String Aggregation"
    You could write a PL/SQL funcrtion to do that for a specific column in a specific table, but [this page|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402] has a couple of different generic solutions that will work on any tables and columns.
    I recommend the first soluton, the user-defined function STRAGG, which you can copy from that page.
    Once you have STRAGG installed, your query can be something like:
    SELECT     s.student_id
    ,     NVL ( STRAGG (t.phone_number)
             , 'No phone'
             )     AS phone_nums
    FROM          student          s
    LEFT OUTER JOIN     telephone     t     ON s.student_id     = t.student_id
    GROUP BY     s.student_id;On Oracle 10 (and up) you may have a similar function, WM_CONCAT (owned by WMSYS), already installed.
    WM_CONCAT is not documented, so you may not want to use it in your Production applications.
    It lokks like
    Edited by: Frank Kulash on Feb 10, 2009 6:31 PM

  • How to export data with column headers in sql server 2008 with bcp command?

    Hi all,
    I want know "how to export data with column headers in sql server 2008 with bcp command", I know how to import data with import and export wizard. when i
    am trying to import data with bcp command data has been copied but column names are not came.
    I am using the below query:-
    EXEC master..xp_cmdshell
    'BCP "SELECT  * FROM   [tempdb].[dbo].[VBAS_ErrorLog] " QUERYOUT "D:\Temp\SQLServer.log" -c -t , -T -S SERVER-A'
    Thanks,
    SAAD.

    Hi All,
    I have done as per your suggestion but here i have face the below problem, in print statment it give correct query, in EXEC ( EXEC master..xp_cmdshell @BCPCMD) it was displayed error message like below
    DECLARE @BCPCMD
    nvarchar(4000)
    DECLARE @BCPCMD1
    nvarchar(4000)
    DECLARE @BCPCMD2
    nvarchar(4000)
    DECLARE @SQLEXPRESS
    varchar(50)
    DECLARE @filepath
    nvarchar(150),@SQLServer
    varchar(50)
    SET @filepath
    = N'"D:\Temp\LDH_SQLErrorlog_'+CAST(YEAR(GETDATE())
    as varchar(4))
    +RIGHT('00'+CAST(MONTH(GETDATE())
    as varchar(2)),2)
    +RIGHT('00'+CAST(DAY(GETDATE())
    as varchar(2)),2)+'.log" '
    Set @SQLServer
    =(SELECT
    @@SERVERNAME)
    SELECT @BCPCMD1
    = '''BCP "SELECT 
    * FROM   [tempdb].[dbo].[wErrorLog] " QUERYOUT '
    SELECT @BCPCMD2
    = '-c -t , -T -S '
    + @SQLServer + 
    SET @BCPCMD
    = @BCPCMD1+ @filepath 
    + @BCPCMD2
    Print @BCPCMD
    -- Print out below
    'BCP "SELECT 
    * FROM   [tempdb].[dbo].[wErrorLog] " QUERYOUT "D:\Temp\LDH_SQLErrorlog_20130313.log" -c -t , -T -S servername'
    EXEC
    master..xp_cmdshell
    @BCPCMD
      ''BCP' is not recognized as an internal or external command,
    operable program or batch file.
    NULL
    if i copy the print ourt put like below and excecute the CMD it was working fine, could you please suggest me what is the problem in above query.
    EXEC
    master..xp_cmdshell
    'BCP "SELECT  * FROM  
    [tempdb].[dbo].[wErrorLog] " QUERYOUT "D:\Temp\LDH_SQLErrorlog_20130313.log" -c -t , -T -S servername '
    Thanks, SAAD.

Maybe you are looking for