Unpivot query error

Hi,
I am running an oracle 11gR2 Database.
I have a table of the structure..
CREATE TABLE "RP_RESOLUTION_MASTER"
( "RM_ID" NUMBER,
"SR_ID" NUMBER,
"REQUEST_STATUS" VARCHAR2(200 BYTE),
"COMMENTS" VARCHAR2(4000 BYTE),
"UPDATED_ON" DATE,
"UPDATED_BY" VARCHAR2(500 BYTE),
"INTERNAL_COMMUNICATION" VARCHAR2(1 BYTE) DEFAULT 'N'
I am running an unpivot query on this.
SELECT *
From Rp_Resolution_Master
Unpivot INCLUDE NULLS (
value For measures In ( rm_id, request_status, Comments
, updated_by, internal_communication)
where sr_id = 1004707
And Updated_On = ( Select Max(Updated_On)
From Rp_Resolution_Master
Where Sr_Id = 1004707);
But I get an error
ORA-01790: expression must have same datatype as corresponding expression
01790. 00000 - "expression must have same datatype as corresponding expression" *Cause:
*Action: Error at Line: 3 Column: 51
What is it that I am doing wrong here?

The columns you're trying to unpivot are not of the same datatype, hence the error.
You have to convert them to a common datatype first :
SQL> select empno, measure, val
  2  from scott.emp
  3  unpivot ( val for measure in (ename, sal) )
  4  where mgr = 7698
  5  ;
unpivot ( val for measure in (ename, sal) )
ERROR at line 3:
ORA-01790: expression must have same datatype as corresponding expression
SQL> with emp2 as (
  2    select empno
  3         , mgr
  4         , ename
  5         , to_char(sal) as sal
  6    from scott.emp
  7  )
  8  select empno, measure, val
  9  from emp2
10  unpivot ( val for measure in (ename, sal) )
11  where mgr = 7698
12  ;
     EMPNO MEASU VAL
      7499 ENAME ALLEN
      7499 SAL   1600
      7521 ENAME WARD
      7521 SAL   1250
      7654 ENAME MARTIN
      7654 SAL   1250
      7844 ENAME TURNER
      7844 SAL   1500
      7900 ENAME JAMES
      7900 SAL   950
10 rows selected.

Similar Messages

  • Package-query: error while loading shared libraries: libcurl.so.4: can

    Hi all
    when i run yaourt to install any things :
    package-query: error while loading shared libraries: libcurl.so.4: cannot open shared object file: No such file or directory
    why?
    what can i do?
    I'm very newbie so help me with easy commands!
    thanks

    try to reinstall yahourt :
    https://wiki.archlinux.org/index.php/Yaourt

  • SAP query error - 1). [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting date and/or time from character string.  'Received Alerts' (OAIB)

    SAP query error - 1). [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting date and/or time from character string.  'Received Alerts' (OAIB)
    SELECT    
    CASE WHEN T0.DocStatus = 'O' THEN 'OPEN'
    WHEN T0.DocStatus = 'C' THEN 'CLOSED'  END  AS 'Document Status',
    T0.DocDate AS 'Posting Date',
    T0.DocNum AS 'Doc.No',
    T0.NumAtCard,
    T0.TransId AS 'Trans. No.',
    T0.Comments AS 'Remarks',
    T0.CardCode AS 'Offset Acct',
    T0.CardName AS 'Offset Acct Name',
    sum(T0.DocTotal) + (T0.WTSum) as 'DocTotal',
    T3.DueDate AS 'Cheque Date',
    T3.CheckSum AS 'Amount'
    FROM         ODPO AS T0 LEFT OUTER JOIN
                          VPM2 AS T1 ON T0.ObjType = T1.InvType AND T0.DocEntry = T1.DocEntry LEFT OUTER JOIN
         OVPM AS T2 ON T2.DocEntry = T1.DocNum LEFT OUTER JOIN
                          VPM1 AS T3 ON T2.DocEntry = T3.DocNum
    where T0.DocDate>='[%0]' and T0.DocDate<='[%1]'

    Hi,
    Try this:
    SELECT   
    CASE WHEN T0.DocStatus = 'O' THEN 'OPEN'
    WHEN T0.DocStatus = 'C' THEN 'CLOSED'  END  AS 'Document Status',
    T0.DocDate AS 'Posting Date',
    T0.DocNum AS 'Doc.No',
    T0.NumAtCard,
    T0.TransId AS 'Trans. No.',
    T0.Comments AS 'Remarks',
    T0.CardCode AS 'Offset Acct',
    T0.CardName AS 'Offset Acct Name',
    sum(T0.DocTotal) + (T0.WTSum) as 'DocTotal',
    T3.DueDate AS 'Cheque Date',
    T3.CheckSum AS 'Amount'
    FROM         ODPO  T0 LEFT OUTER JOIN
                          VPM2  T1 ON T0.ObjType = T1.InvType AND T0.DocEntry = T1.DocEntry
    LEFT OUTER JOIN
         OVPM  T2 ON T2.DocEntry = T1.DocNum LEFT OUTER JOIN
                          VPM1  T3 ON T2.DocEntry = T3.DocNum
    where T0.DocDate >= '[%0]' and T0.DocDate <='[%1]'
    group by T0.DocStatus,T0.DocDate ,
    T0.DocNum ,
    T0.NumAtCard,
    T0.TransId ,
    T0.Comments ,
    T0.CardCode,
    T0.CardName ,
    T0.WTSum ,
    T3.DueDate ,
    T3.CheckSum
    Thanks & Regards,
    Nagarajan

  • Invalid LOV query error

    I am trying to modify a query for LOV page item but get an Invalid LOV query error when trying to Apply Changes to my page(query however works in SQL*Plus)
    I am trying to change the date format of query result to MON YYYY.
    Original query that works:
    select distinct bill.BILLED_DATE display_value, bill.BILL_ID return_value
    from BILL;
    New Query that fails in APEX (but works in SQL*Plus)
    select distinct to_char(bill.BILLED_DATE, 'MON YYYY') display_value,
    bill.BILL_ID return_value from BILL;
    Anyone have any idea what I need to do to make this work?
    "1 error has occurred
    LOV query is invalid, a display and a return value are needed, the column names need to be different. If your query contains an in-line query, the first FROM clause in the SQL statement must not belong to the in-line query"

    Strange, this lov does work and is no different than yours:
    select distinct to_char(sysdate,'MON YYYY') disp, 1 retval from dual
    What are the results from the query? Can there be something wrong with that?
    Regards Guido

  • Query erroring out with lack of temp space?

    I have 2 databases. One was cloned from the other on to another server.
    On one server the query takes 5 seconds to run on the other server the query errors lack with lack of disk space.
    The init files are the same. The Oracle memory is the same. The temp tablespace size is the same.
    I'm stuck!
    What should I look for to find out what is causing the error?

    On both databases the version is 9.2.0.6.
    This is the view that worked in database1 and errored in database2...
    CREATE OR REPLACE VIEW SAP_STAGE.MTC_STG_MEASURE_POINT_V
    EQUIP_NO,
    MEASUR_PNTPOS,
    CHARACT_NAME,
    UNIT,
    MEASUR_PNT_DESC,
    VALUATION_CODE,
    TEXT_FIELD
    AS
    SELECT DISTINCT xref.equnr AS equip_no, rpmp.*
    FROM sap_stage.measuring_point mp JOIN xref_sap_equi xref
    ON TRIM (mp.equip_no) = TRIM (xref.groes)
    JOIN stg_mtc_msf600 msf600
    ON TRIM (mp.equip_no) = TRIM (msf600.equip_no)
    AND TRIM (msf600.dstrct_code) in ('347','315')
    JOIN rec_prodstat_code_measur_pts rpmp ON 1 = 1
    If I qualify all the tables with SAP_STAGE the query runs in 5 seconds in database2.
    Why does the query run in database 1 without the schema names?

  • Query Error (CL_RSDD_VCUBE .and SAPLRRK0)

    Query Error (CL_RSDD_VCUBE .and SAPLRRK0)  
    Posted: Apr 19, 2007 6:01 PM         Reply      E-mail this post 
    Hi,
    I'm trying yo run a query.
    I check the query in the Query Designer and is OK, but when run the query a message appears "Internal error in program CL_RSDD_VCUBE and method GET_SID-8-" and "System error in program SAPLRRK0 and form RSRDR;SRRK0F30-01-".
    This query is made on Remote cube Accessing data from ORACLE through UD Connect , and I don't known if this error is related number of records.We r using BW3.5
    We have OPCO CODE as a infoobject in the query if we restrict that opcocode with some values and execue the query its getting the values and running without errors .But if we wont restrict with anyvalues on the opo code its getting above errors.
    Can anyone help me?
    Thanks in Advance
    Message was edited by:
    Mural

    Hi Mural,
    you can go in Tcode RSRT, introduce your query and then select from Environment first "Repair Read Mode" and then "Generate Queries". Then try click to Execute to see if it was only a generation problem or if the query has a real problem.
    In this case you can try with "Execute + Debug" to see where the problem is.
    Ciao.
    Riccardo.

  • Generate causes SCC Query Error: Unhandled exception

    Hi folks,
    I have Robohelp X5, I am composing on my local machine with
    saves going to an RCS server. I've pretty much figured out that RCS
    has a problem with the skins in Robohelp, because if I go to create
    a custom skin, I can create it in a non-controlled project. The
    second I go to create a custom skin in the controlled version, I
    get an infinite loop of the SCCQueryError message, Unhandled
    Exception Message Boxes. I have to kill Robohelp, and reboot to get
    out of the error message.
    Whenever I go to generate the verson controlled project, I
    get at least six of these error messages, but the project is
    generated and I can open it and can't seem to find anything
    missing. So, even though I get the errors in a generate, they don't
    affect the ability to generate a project.
    I've already checked to be sure that the RCS server is
    accepting all the file extensions.. that was my first thought was
    that it didn't like the .swf extensions.
    Anyone else have or see this problem?
    Thanks!

    Thank you Eilsa... It's a touch complicated, but I am working
    off my hard drive, and Robohelp is installed on my hard drive. The
    webhelp file that is integrated with the project is being pushed to
    the a folder on the development server where RCS resides, and my
    project files are being archived in another directory on the RCS
    version tracker.
    I get the SCC query error (which seems to be an RCS version
    tracker error) right after I generate either a local or server
    webhelp, about six in all. So I'm thinking that there is some file
    extension that RCS is blocking, because I don't get the errors when
    I do the same thing with a non-version tracked project.
    Forget about trying to create any skins.. (and this is on my
    local, too) I have to switch to a non-version tracked project to
    create the skins.
    But just trying to see if anyone else has seen the
    problem..

  • BEX query error---Error reading the data of InfoProvider

    Hello all,
    we are getting the following msg when we execute the query-
    Error reading the data of InfoProvider ZEUDPR01
    Errors occurred when extracting data from DataSource 9AEU_DOM
    Short Text: Error for COM routine using application program (return c
    Parameter: 1028533- LC kernel
    Message in Source System: E102(/SAPAPO/OM) ...
    Short Text: COM - error Unknown
    Parameter: Unknown
    Message in Source System: E001(/SAPAPO/OM) ...
    Messages for DataSource 9AEU_DOM from source system PA1CLNT100
    Errors occurred during parallel processing of query 4, RC: 3
    Error while reading data; navigation is possible
    Row: 54 Inc: WRITE_MESSAGES Prog: CL_RSDR_AT_QUERY
    Found
    This is the error observed for a particular selection only..for rest of the selection we get the data correctly.
    Please help with the possible causes of error.
    Thanks,
    Pallavi

    Hi Pallavi,
    How did you manage the pb?
    we have the same error after Stack 21 (SP23)
    we could not run query.
    Thanks.
    John

  • 특정 SUPPLIER SITE LEVEL의 DATA수정 시도시 RE-QUERY ERROR

    제품 : FIN_AP
    작성날짜 : 2004-05-19
    특정 SUPPLIER SITE LEVEL의 DATA수정 시도시 RE-QUERY ERROR
    =================================================
    Problem Description
    특정 Supplier Site level의 Data수정 시도시 아래의 Message발생
    ==============================================
    record has been updated, re-query block to see change
    ==============================================
    Solution Description
    아래의 SQL을 실행해서 "CHK_TRAIL_SPACE"라는 Procedure를
    만든 후 생성된 Procedure를 다음의 방법으로 실행하면, Input Table의
    어떤 Column에 NULL문자가 들어갔는지 확인할 수 있다.
    set serveroutput on
    execute chk_trail_space(<table_name to check>);
    i.e. (execute chk_trail_space('PO_VENDORS');)
    trailspace.sql:
    ===============================================================================
    CREATE OR REPLACE PROCEDURE CHK_TRAIL_SPACE (p_table_name in varchar)
    IS
    v_table_name varchar(30);
    v_column_name varchar(30);
    v_column_name_c char(30);
    v_space_count number;
    v_ret number; -- temp holder for above
    v_initial_space_counter number;
    dyn_cursor number;
    CURSOR TABLE1 IS
    SELECT table_name
    FROM DBA_TABLES
    WHERE table_name = p_table_name;
    CURSOR COLUMN1 IS
    SELECT column_name
    FROM DBA_TAB_COLUMNS
    WHERE table_name = v_table_name;
    BEGIN
    OPEN TABLE1;
    LOOP
    -- FOR crec1 in TABLE1 LOOP
    fetch TABLE1 into v_table_name;
    IF (TABLE1%NOTFOUND) THEN
    exit;
    END IF;
    dbms_output.put_line(v_table_name);
    dbms_output.put_line
    v_initial_space_counter := 0;
    OPEN COLUMN1;
    LOOP
    -- FOR crec2 in COLUMN1 LOOP
    fetch COLUMN1 into v_column_name;
    IF (COLUMN1%NOTFOUND) THEN
    exit;
    END IF;
    dyn_cursor := DBMS_SQL.OPEN_CURSOR;
    DBMS_SQL.PARSE
    (dyn_cursor,
    'SELECT COUNT(*) ' ||
    'FROM ' || p_table_name ||
    ' WHERE ' || v_column_name || ' LIKE ''% ''',
    DBMS_SQL.NATIVE);
    DBMS_SQL.define_column (dyn_cursor, 1, v_space_count);
    v_ret := DBMS_SQL.EXECUTE(dyn_cursor);
    if DBMS_SQL.fetch_rows(dyn_cursor) > 0 then
    DBMS_SQL.column_value (dyn_cursor, 1, v_space_count);
    end if;
    DBMS_SQL.CLOSE_CURSOR(dyn_cursor);
    IF v_space_count > 0 THEN
    v_initial_space_counter := v_initial_space_counter + 1;
    END IF;
    v_column_name_c := v_column_name;
    IF v_space_count > 0 THEN
    dbms_output.put_line(' ' || v_column_name_c || to_char(v_space_count))&
    #059;
    END IF;
    end loop;
    close column1;
    end loop;
    close table1;
    END CHK_TRAIL_SPACE;
    ====================================================================
    NULL문자가 들어간 Column이 확인되면,
    update po_vendors
    set vendor_name = rtrim(vendor_name);
    위의 방법으로 수정하면 된다.
    Reference Documents
    Note :234048.1

    If I delete the purchase details/line item, the supplier site can be changed.
    The error appeared again after the new line item selected,click on "Shipment" button, and change the supplier site.
    It's not able to change it. Any reason caused by the line item shipment? how it relate?

  • ADM Error processing results from query: Error: Index 0 out of range

    11.1.2.1
    When running quite a large book, we are getting the following error:
    ADM Error processing results from query: Error: Index 0 out of range
    The individual reports in the books are running fine.
    PS.  The report books that are giving this error run fine on 9.3.1
    Could this be a time-out issue and how do we resolve it?

    what is background datasource Essbase or HFM
    do you have lot of data in pov please try below
    >Do you have pov prompt
    >increase jvm heap size for report server in reporting server
    >Fr log files has some more detail

  • Query error - with filtering records

    Hi. I have a gallery that shows 9 records at a time, which
    you can then move on to subsequent pages. I added filters to narrow
    down the record search, however, I am receiving query errors. This
    is my code:
    <!----- This is setting the initial defaults for the filter
    variables ---->
    <cfparam name="form.ART_CATEGORY_ID" default="">
    <cfparam name="form.ART_TYPE_ID" default="">
    <cfparam name="form.FINE_ART_CLASS_ID" default="">
    <cfparam name="form.searchfield" default="">
    <!----- Populate the CATEGORIES filter drop-down ---->
    <cfquery name="categories" datasource="nancy">
    SELECT *
    FROM CATEGORIES
    ORDER BY ART_CATEGORY_ID
    </cfquery>
    <!----- Populate the TYPES filter drop-down ---->
    <cfquery name="types" datasource="nancy">
    SELECT *
    FROM TYPE
    ORDER BY ART_TYPE_ID
    </cfquery>
    <!----- Populate the CLASS filter drop-down ---->
    <cfquery name="class" datasource="nancy">
    SELECT *
    FROM CLASS
    ORDER BY FINE_ART_CLASS_ID
    </cfquery>
    <!----- Create the filter drop-down selections ---->
    <form method="post" action="root_fineart.cfm">
    <select name="ART_TYPE_ID">
    <option value="" <cfif trim(form.ART_TYPE_ID) eq
    "">selected
    </cfif>> All </option>
    <cfoutput query="types">
    <option value="#ART_TYPE_ID#"
    <cfif form.ART_TYPE_ID eq
    types.ART_TYPE_ID>selected</cfif>>#ART_TYPE#</option>
    </cfoutput>
    </select>
    <select name="ART_CATEGORY_ID">
    <option value="" <cfif trim(form.ART_CATEGORY_ID) eq
    "">selected
    </cfif>> All </option>
    <cfoutput query="categories">
    <option value="#ART_CATEGORY_ID#"
    <cfif form.ART_CATEGORY_ID eq
    categories.ART_CATEGORY_ID>selected</cfif>>#ART_CATEGORY#</option>
    </cfoutput>
    </select>
    <select name="FINE_ART_CLASS_ID">
    <option value="" <cfif trim(form.FINE_ART_CLASS_ID) eq
    "">selected
    </cfif>> All </option>
    <cfoutput query="class">
    <option value="#FINE_ART_CLASS_ID#"
    <cfif form.FINE_ART_CLASS_ID eq
    class.FINE_ART_CLASS_ID>selected</cfif>>#FINE_ART_CLASS#</option>
    </cfoutput>
    </select>
    <!----- This also creates a SEARCH capability ---->
    <input name="searchfield" type="text" size="10"
    value="#form.searchfield#" /></cfoutput> </label>
    <input name="submit" type="submit" value="Submit" />
    <!----- I got this part of the code from a site, that allows
    me to display the 9 records at a time in my gallery ---->
    <cfparam name="start" type="numeric" default="1">
    <cfparam name="step" type="numeric" default="9">
    <!----- My query to retrieve the records... This may be where
    I have something wrong... ---->
    <cfquery datasource="nancy" cachedwithin=".01"
    name="queryResults">
    SELECT *
    FROM ART
    WHERE 1 = 1
    <cfif val(form.ART_CATEGORY_ID) GT 0>
    AND ART_CATEGORY_ID = <cfqueryparam
    value="#form.ART_CATEGORY_ID#" cfsqltype="cf_sql_integer">
    </cfif>
    <cfif val(form.ART_TYPE_ID) GT 0>
    AND r.ART_TYPE_ID = <cfqueryparam
    value="#form.ART_TYPE_ID#" cfsqltype="cf_sql_integer">
    </cfif>
    <cfif val(form.FINE_ART_CLASS_ID) GT 0>
    AND i.FINE_ART_CLASS_ID = <cfqueryparam
    value="#form.FINE_ART_CLASS_ID#" cfsqltype="cf_sql_integer">
    </cfif>
    <cfif trim(form.searchfield) neq "">
    AND ART_TITLE LIKE '%#form.searchfield#%'
    </cfif>
    ORDER BY ART_TITLE ASC
    </cfquery>
    <!----- This is also code I got somewhere else to display the
    gallery ---->
    <cfif queryResults.recordcount gt 0>
    <cfoutput>
    <p class="style1">
    <!--- if past start --->
    <cfif (start-step-step) gt 1>
    <a href="#cgi.SCRIPT_NAME#?start=1"><img
    src="images/Beginning_blue.png" alt="Beginning" width="31"
    height="21" align="absbottom" /></a>
    </cfif>
    <cfif start gt 1>
    <a href="#cgi.SCRIPT_NAME#?start=#start-step#"><img
    src="images/previous_blue.png" alt="Previous" align="absbottom"
    /></a>
    </cfif>
    <strong>#start# - #iif(start * 3 + step gt
    queryResults.recordcount,queryResults.recordcount,start + step-1)#
    of #queryResults.recordcount# records</strong>
    <!--- if still some not displayed --->
    <cfif (start + step) lte queryResults.recordcount>
    <a href="#cgi.SCRIPT_NAME#?start=#start+step#"><img
    src="images/next_blue.png" alt="Next" align="absbottom"
    /></a>
    </cfif>
    <cfif (start+step+step) lte queryResults.recordcount>
    <a
    href="#cgi.SCRIPT_NAME#?start=#queryResults.recordcount-step+1#"><img
    src="images/end_blue.png" alt="End" align="absbottom"
    /></a>
    </cfif>
    </p>
    </cfoutput>
    </cfif>
    <cfloop query="queryResults" startrow="#start#"
    endrow="#start + step/3-1#">
    <table width="100%" border="1" bordercolor="#FFFFFF"
    cellspacing="0" cellpadding="2">
    <tr> <cfoutput query="queryResults"
    startrow="#start#" maxrows="3">
    <td width="33%"
    class="style1">#queryResults.ART_TITLE#</td>
    </cfoutput>
    <cfset #start# = #start# + 3>
    </tr>
    </table>
    </cfloop>
    </td>
    </tr>
    </table></form>
    It seems that the CATEGORIES filter is the only one that does
    not return a ERROR EXECUTING DATABASE QUERY error. However, it does
    not filter all the records... it only seems to filter and return
    the first 4 or 5 records.
    Any thoughts?

    your queryResults query selects only from ART table, while in
    the WHERE
    clause you are apparently using other tables whihc are not in
    your FROM
    clause...
    you need to use JOIN/INNER JOIN/LEFT JOIN/RIGHT JOIN in your
    FROM clause
    to link the other tables. check your db manual for proper
    usage of those
    operators.
    Azadi Saryev
    Sabai-dee.com
    http://www.sabai-dee.com/

  • HOW TO FIND AND CORRECT THE SQL QUERY ERRORS ????

    Sometimes I get the errors while executing the sql queries.
    I just wanted to know about the various ways by which I can find the sql query errors .
    Any suggestions will be deeply appreciated.

    If you get the an error from SSMS and you can't comprehend it, you can google the error message and google would always lead you to the correction. Or you can post the error in this forum, people
    here are always kind and ready to help :).
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • SharePoint 2010 Unable to execute query: Error 0x80131530

    I am seeing the below error message in the ULS logs while accessing some set of items in the list and the item will not get
    opened after long tim. 
    "Unable to execute query: Error 0x80131530
    Unknown SPRequest error occurred. More information: 0x80131530
    System.Web.HttpException: Request timed out."
    This list has 202 items in total with 45 columns in total (includes
    5 lookup columns, 3 append history columns). 
    Items which has more than 20 versions is not loading.
    In the same site, there is another list of the same template with 2009 items and some items with more
    than 80 versions works fine.
    Please let me know if you have any suggestion to fix this.

    Yes there are 2 simple SPD workflows. One of the workflow operation is to send email and other one is to create an item in another based on condition.
    The other list which works fine also has similar SPD workflows. 

  • Query Error - Schema Does Not Exist

    I get the following error when creating stored procedure:
    Msg 2797, Level 16, State 1, Procedure SearchAllTables, Line 90
    The default schema does not exist.
    CREATE PROC SearchAllTables
    @SearchStr nvarchar(100)
    AS
    BEGIN
    CREATE TABLE #Results(TableName nvarchar(370), KeyValues nvarchar(3630), ColumnName nvarchar(370), ColumnValue nvarchar(3630))
    SET NOCOUNT ON
    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
        ,@TableShortName nvarchar(256)
        ,@TableKeys nvarchar(512)
        ,@SQL nvarchar(3830)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
    WHILE @TableName IS NOT NULL
    BEGIN
        SET @ColumnName = ''
        -- Scan Tables
        SET @TableName = 
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM    INFORMATION_SCHEMA.TABLES
            WHERE       TABLE_TYPE = 'BASE TABLE'
                AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        Set @TableShortName=PARSENAME(@TableName, 1)
        -- print @TableName + ';' + @TableShortName +'!' -- *** DEBUG LINE ***
            -- LOOK Key Fields, Set Key Columns
            SET @TableKeys=''
            SELECT @TableKeys = @TableKeys + '''' + QUOTENAME([name]) + ': '' + CONVERT(nvarchar(250),' + [name] + ') + ''' + ',' + ''' + '
             FROM syscolumns 
             WHERE [id] IN (
                SELECT [id] 
                 FROM sysobjects 
                 WHERE [name] = @TableShortName)
               AND colid IN (
                SELECT SIK.colid 
                 FROM sysindexkeys SIK 
                 JOIN sysobjects SO ON 
                    SIK.[id] = SO.[id]  
                 WHERE 
                    SIK.indid = 1
                    AND SO.[name] = @TableShortName)
            If @TableKeys<>''
                SET @TableKeys=SUBSTRING(@TableKeys,1,Len(@TableKeys)-8)
            -- Print @TableName + ';' + @TableKeys + '!' -- *** DEBUG LINE ***
        -- Search in Columns
        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND TABLE_NAME  = PARSENAME(@TableName, 1)
                    AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                    AND QUOTENAME(COLUMN_NAME) > @ColumnName
            ) -- Set ColumnName
            IF @ColumnName IS NOT NULL
            BEGIN
                SET @SQL='
                    SELECT 
                        ''' + @TableName + '''
                        ,'+@TableKeys+'
                        ,''' + @ColumnName + '''
                    ,LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                --Print @SQL -- *** DEBUG LINE ***
                INSERT INTO #Results
                    Exec (@SQL)
            END -- IF ColumnName
        END -- While Table and Column
    END --While Table
    SELECT TableName, KeyValues, ColumnName, ColumnValue FROM #Results
    END

    Here is the code from my blog post:
    CREATE PROCEDURE spSearchStringInTable
    (@SearchString NVARCHAR(MAX),
    @Table_Schema sysname,
    @Table_Name sysname)
    AS
    BEGIN
    DECLARE @Columns NVARCHAR(MAX), @Cols NVARCHAR(MAX), @PkColumn NVARCHAR(MAX)
    -- Get all character columns
    SET @Columns = STUFF((SELECT ', ' + QUOTENAME(Column_Name)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE DATA_TYPE IN ('text','ntext','varchar','nvarchar','char','nchar')
    AND TABLE_NAME = @Table_Name
    ORDER BY COLUMN_NAME
    FOR XML PATH('')),1,2,'')
    IF @Columns IS NULL -- no character columns
    RETURN -1
    -- Get columns for select statement - we need to convert all columns to nvarchar(max)
    SET @Cols = STUFF((SELECT ', cast(' + QUOTENAME(Column_Name) + ' as nvarchar(max)) as ' + QUOTENAME(Column_Name)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE DATA_TYPE IN ('text','ntext','varchar','nvarchar','char','nchar')
    AND TABLE_NAME = @Table_Name
    ORDER BY COLUMN_NAME
    FOR XML PATH('')),1,2,'')
    SET @PkColumn = STUFF((SELECT N' + ''|'' + ' + ' cast(' + QUOTENAME(CU.COLUMN_NAME) + ' as nvarchar(max))'
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
    INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU ON TC.TABLE_NAME = CU.TABLE_NAME
    AND TC.TABLE_SCHEMA = CU.TABLE_SCHEMA
    AND Tc.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
    WHERE TC.CONSTRAINT_TYPE ='PRIMARY KEY' AND TC.TABLE_SCHEMA = @Table_Schema AND TC.TABLE_NAME = @Table_Name
    ORDER BY CU.COLUMN_NAME
    FOR XML PATH('')),1,9,'')
    IF @PkColumn IS NULL
    SELECT @PkColumn = 'cast(NULL as nvarchar(max))'
    -- set select statement using dynamic UNPIVOT
    DECLARE @SQL NVARCHAR(MAX)
    SET @SQL = 'select *, ' + QUOTENAME(@Table_Schema,'''') + 'as [Table Schema], ' + QUOTENAME(@Table_Name,'''') + ' as [Table Name]' +
    ' from
    (select '+ @PkColumn + ' as [PK Column], ' + @Cols + ' FROM ' + QUOTENAME(@Table_Schema) + '.' + QUOTENAME(@Table_Name) + ' )src UNPIVOT ([Column Value] for [Column Name] IN (' + @Columns + ')) unpvt
    WHERE [Column Value] LIKE ''%'' + @SearchString + ''%'''
    --print @SQL
    EXECUTE sp_ExecuteSQL @SQL, N'@SearchString nvarchar(max)', @SearchString
    END
    GO
    IF OBJECT_ID('TempDB..#Result', N'U') IS NOT NULL DROP TABLE #Result;
    CREATE TABLE #RESULT ([PK COLUMN] NVARCHAR(MAX), [COLUMN VALUE] NVARCHAR(MAX), [COLUMN Name] sysname, [TABLE SCHEMA] sysname, [TABLE Name] sysname)
    DECLARE @Table_Name sysname, @SearchString NVARCHAR(MAX), @Table_Schema sysname
    SET @SearchString = N'Cost'
    DECLARE curAllTables CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY
    FOR
    SELECT Table_Schema, Table_Name
    FROM INFORMATION_SCHEMA.Tables
    WHERE TABLE_TYPE = 'BASE TABLE'
    ORDER BY Table_Schema, Table_Name
    OPEN curAllTables
    FETCH curAllTables
    INTO @Table_Schema, @Table_Name
    WHILE (@@FETCH_STATUS = 0) -- Loop through all tables in the database
    BEGIN
    INSERT #RESULT
    EXECUTE spSearchStringInTable @SearchString, @Table_Schema, @Table_Name
    FETCH curAllTables
    INTO @Table_Schema, @Table_Name
    END -- while
    CLOSE curAllTables
    DEALLOCATE curAllTables
    -- Return results
    SELECT * FROM #RESULT ORDER BY [Table Name]
    It works OK for me.
    I also posted another code today which searches a single column in all tables of the database. I spent about an hour working on that code and it works fine for me too.
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • SQL Query error in java swing Application

    hi,
    I'm getting the following error when i try to manipulate the date in query.I have set of tuples and would like to retrieve with respect to the date given.Please do help me to get rid of this error.This is the error.
    MY QUERY:
    ResultSet rsdate=st1.executeQuery("select * from phy_stock where date = "+d1+"");
    Where d1 is given like this:
    String startdate[2]="11/31/2008";
    DateFormat df = new SimpleDateFormat ("MM/dd/yyyy"); //converting a string to DATE format.
    Date d1 = df.parse(startdate[2]);
    ERROR:
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'date = Mon Sep 01 00:00:00 IST 2008'
    thanks,
    kumar.

    Dates do not have formats. When referencing a Date in String concatenation, which is what you are doing here,
    ResultSet rsdate=st1.executeQuery("select * from phy_stock where date = " + d1 + "");you will get what Date's toString method produces, which will not work for that (or any) query. For one, it wouldn't be surrounded by single quotes ('), and for two, the String format of the Date would not be acceptable by the DB (unless you had changed the DBs defaults).
    Use a PreparedStatement, as suggessted above, and this problem goes away.
    Edit: And make sure to use the setDate method, of course.

Maybe you are looking for