SQL query to get DDL for Adding PK.

Guys,
I'm looking for SQL query that gets me the "ALTER TABLE <TABLE_NAME> ADD CONSTRAINT <constraint_name> PRIMARY KEY (X,Y,...);" statments of all tables in my schema containing Primary Keys.
Could someone help me with the query please?
Regards,
Bhagat

You need this
SELECT 'ALTER TABLE '||table_name||' ADD CONSTRAINT '||constraint_name||' PRIMARY KEY ('||column_name||');'
  FROM ( SELECT uc.table_name
               ,uc.constraint_name
               ,RTRIM (XMLAGG (XMLELEMENT (ucc, column_name || ',')).extract ('//text()'), ',')  column_name
          FROM user_constraints        uc
              ,user_cons_columns       ucc
         WHERE uc.constraint_type      = 'P'
           AND uc.constraint_name      = ucc.constraint_name
      GROUP BY uc.table_name
              ,uc.constraint_name
ORDER BY table_name;   Regards
Arun

Similar Messages

  • SQL query to get a list of relations between workitems

    How can I create a SQL query to get a list of all problems with related changes?  And all problems with related incidents?
    I have tried to join the tables RelationshipTypeDim with ProblemDimKey and ChangeRequestDim, but the results are not correct.

    The relationships in the data warehouse can be kind of tricky. The relationships are contained in the WorkItemRelatesToWorkItemFactvw table. This table lists the related items by their WorkItemDimKey, so you cannot reference directly from the ChangeRequestDimvw
    or ProblemDimvw. You will need to reference the WorkItemDimvw to get the WorkItemDimKey for each entry.
    The query below will get all of the related work items from the Change Request class. The way the joins work is ChangeRequestDimvw gets the list of change requests. Then inner joins WorkItemDimvw to get the WorkItemDimKey for each CR. Then inner joins WorkItemRelatesToWorkItemFactvw
    to get all of the CRs with related work items. Then inner joins the WorkItemDimvw again to get the ID of the related work item. 
    Now the tricky part is it appears that these relationship are set based on which item  that created the relationship. So you need to union a second query that reverse the relationship on the WorkItemRelatesToWorkItemFactvw. 
    This query should give you a good start on getting the related work items. You can filter it down from here if you only want to include problems.
    SELECT C.ID, WIWI.ID
    FROM dbo.ChangeRequestDimvw C
    INNER JOIN dbo.WorkItemDimvw WI ON
    WI.EntityDimKey = C.EntityDimKey
    INNER JOIN dbo.WorkItemRelatesToWorkItemFactvw AS WIRWI ON
    WIRWI.WorkItemDimKey = WI.WorkItemDimKey
    INNER JOIN dbo.WorkItemDimvw AS WIWI ON
    WIWI.WorkItemDimKey = WIRWI.WorkItemRelatesToWorkItem_WorkItemDimKey
    union
    SELECT C.ID, WIWI.ID
    FROM dbo.ChangeRequestDimvw C
    INNER JOIN dbo.WorkItemDimvw WI ON
    WI.EntityDimKey = C.EntityDimKey
    INNER JOIN dbo.WorkItemRelatesToWorkItemFactvw AS WIRWI ON
    WIRWI.WorkItemRelatesToWorkItem_WorkItemDimKey = WI.WorkItemDimKey
    INNER JOIN dbo.WorkItemDimvw AS WIWI ON
    WIWI.WorkItemDimKey = WIRWI.WorkItemDimKey
    Order by C.ID
    Matthew Dowst |
    Blog | Twitter

  • Sql query to get distinct count

    Hi
    I use SQL Server Management Studio
    can I have a sql query to get count as shown below against  each month column and name column to get distinct count.
    for example if there is two rows with the same date period and same name then the count should be one in first row and zero in the next row of the same data.
    Table Name: Table1
    Column: Month, Name
    Month
    Name
    Count
    12/1/2012 0:00
    AK
    1
    12/1/2012 0:00
    AK
    0
    12/1/2012 0:00
    AB
    1
    1/1/2013 0:00
    AK
    1
    1/1/2013 0:00
    AK
    0
    1/1/2013 0:00
    AB
    1
    3/1/2013 0:00
    AA
    1
    3/1/2013 0:00
    AK
    1
    3/1/2013 0:00
    AK
    0
    6/1/2013 0:00
    AA
    1
    6/1/2013 0:00
    AK
    1
    6/1/2013 0:00
    AK
    0
    9/1/2013 0:00
    AA
    1
    9/1/2013 0:00
    AK
    1
    9/13/2013 0:00
    AK
    1
    10/1/2013 0:00
    AA
    1
    10/1/2013 0:00
    AK
    1
    10/1/2013 0:00
    AK
    0

    Hi,
    Thanks for the query but this query gives the total count like shown below
    if see the second row in the below table AK for 2012-12-1 gives total count as 2 but need the query to show the first row as 1 and there after 0
    query result
    Month name cnt
    2012-12-01 00:00:00.000 AB 1
    2012-12-01 00:00:00.000 AK 2
    2012-12-01 00:00:00.000 AK 2
    2013-01-01 00:00:00.000 AB 1
    2013-01-01 00:00:00.000 AK 2
    2013-01-01 00:00:00.000 AK 2
    2013-03-01 00:00:00.000 AA 1
    2013-03-01 00:00:00.000 AK 2
    2013-03-01 00:00:00.000 AK 2
    2013-06-01 00:00:00.000 AA 1
    2013-06-01 00:00:00.000 AK 2
    2013-06-01 00:00:00.000 AK 2
    2013-09-01 00:00:00.000 AA 1
    2013-09-01 00:00:00.000 AK 1
    2013-09-13 00:00:00.000 AK 1
    2013-10-01 00:00:00.000 AA 1
    2013-10-01 00:00:00.000 AK 2
    2013-10-01 00:00:00.000 AK 2

  • SQL query to get the Datetime 06 hours prior to the table Datetime value

    Hi Experts,
                    I'm just trying to create a SQL query to get the Datetime which should be 06 hours prior to my Table column value(Executiontime),
    Eg: my Executiontime(column) value is 07:00AM means, this query should fetch the detail of first VMName from table at 01:00AM, 
    SQL Table Name: TestTable
    Columns: VMName(varchar),status(varchar) Executiontime(Datetime)
    SQL Query : Select Top 1 VMName from
    TestTable where convert(date,Exeutiontime)=convert(date,getdate()) and
    status='0' and ExecutionTime > dateadd(hour,6,getdate())
    Request someone to alter this Query to my requirement or give me the new one.
    Regards,
    Sundar
    Sundar

    Hi All,
            Thanks for your Prompt response. I tried the below queries, but still I don't have any luck. Actually the queries are returning the value before the condition met (say when the time difference is more than 06 hours). I want the
    query to return exactly @ 06 hour difference or less than 06 hours,
    Query 01: Select Top 1 VMName from TestTable where
    convert(date,Exeutiontime)=convert(date,getdate())
    and status='0'
    and ExecutionTime >
    dateadd(hour,-6,getdate())
    Query 02: Select
    Top 1 VMName from TestTable where
    status='0'
    and ExecutionTime >
    dateadd(hour,-6,getdate())
    Query 03: Select
    Top 1 VMName from TestTable where status='0'
    and ExecutionTime >
    dateadd(hour,-6,ExecutionTime)
              Can someone point out the mistake please.
    Regards,
    Sundar
    Sundar

  • SQL query to get the list of approvals

    Hi,
    Could someone let me know the SQL query to get the list of all the pending approvals for a user in OIM 11g R2.
    Thanks

    There are a few ways to do this:
    -  The easiest would be to use a Relationship Query from the CMC. To do this, go to the Universes section on the CMC, right click on the relevant universe, select tools >> Check Relationships.
    - Use Query Builder. You will need more than one query to pull the information you need. You could try something like the below (for Webi)
    SELECT SI_NAME, SI_WEBI, SI_DATACONNECTION FROM CI_APPOBJECTS
    WHERE SI_KIND = 'universe' and SI_NAME = 'Universe Name'
    This will give you a list of Webi Reports by SI_ID.
    You'll need another query to list Webi report names:
    SELECT SI_NAME FROM CI_INFOOBJECTS WHERE SI_ID IN (SI_ID from query above)
    - This is trivial via Auditing / the Activity universe. This of course will only return reports that have already run.
    Best.
    Srinivas

  • SQL query to get last 10 records in the table?

    Hi,
    Can anyone tell me the SQL query to get last 10 records in the table?
    Thanks!!
    MCP

    Please, define what "last" means. Sets are unordered by definition, so if you want to retrieve rows from a table in a specific order you need to specify what that order is - e.g. by maintaining a value in a column (or a combination of columns) that you can use in the ORDER BY clause of the SELECT statement.
    If, for instance, you kept the time when the row was inserted in a special column (InsertedTime), you could use this in your query like this:
    select top (10)
      <column list>
      from <table or view>
      where <restriction(s)>
      order by InsertedTime desc;
    ML
    Matija Lah, SQL Server MVP
    http://milambda.blogspot.com

  • Dear Gurus, Can i have SQL query to get Ar cash receipt appled lines details in R12

    Dear Gurus, Can i have SQL query to get Ar cash receipt appled lines details in R12

    I need to get ar and ap details from GL through xla.For ex: Reference1,reference2,reference3,reference4,reference 5, in 11i these column values are displayed in gl_je_lines where as in R12 we need to join xla tables with gl_sl_link_id and gl_sl_link_table
    Can someone provide query to get subledger details particularly ar and ap?.How are the AP & GL Journal Tables linked? [ID 1188714.1]
    R12 Mapping Between Subledger Tables, SLA and GL Tables [ID 871622.1]
    eTRM
    http://etrm.oracle.com/
    Thanks,
    Hussein

  • SQL query to get transaction detail from DEFERRED_TRAN_ID

    Hi,
    I'm using Oracle Advance Replication and get the transaction detail from Enterprise Manager Console.
    So instead of using the console.
    Is there a way any SQL query which get transaction details like SQL query fired, old and new column value etc from DEFERRED_TRAN_ID.
    thanks

    quote:
    Originally posted by:
    lucapac
    I have two tables: tblWorkers and tblSkills. tblWorkers has a
    column, Skills, which is populated from a multiple-checkbox form
    field with one or more skill_IDs from tblSkills, so each
    tblWorkers.Skills consists of a list of one or more comma-delimited
    values. For any Skill_ID, I need to generate a listing of all
    Workers with the corresponding skill, so I have tried to do
    something along the lines of SELECT WorkerName FROM tblWorkers
    WHERE Skills IN (Skills, #FORM.Skill_ID#) ... or WHERE Skills IN
    (ListFind(Skills, #FORM.Skill_ID#)) ... etc. ??? My results (once I
    got data type mismatches out of the way) return all Workers, not
    just those with the desired Skill. There must be an easy way to do
    this ... How do people with a bit more CF/SQL experience than I
    have do this???
    As Kronin implied, we normalize our databases. If you don't
    understand that answer, the book "Database Design for Mere Mortals"
    is often mentioned on this forum.

  • SQL Query to get Project Plan Name and Resource Name from Reporting database of Project Server 2007

    Can you please help me to write an SQL Query to get Project Plan Name and Resource Name from Reporting database of Project Server 2007. Thanks!!

    Refer
    http://gallery.technet.microsoft.com/projectserver/Server-20072010-SQL-Get-a99d4bc6
    SELECT
    dbo.MSP_EpmAssignment_UserView.ProjectUID,
    dbo.MSP_EpmAssignment_UserView.TaskUID,
    dbo.MSP_EpmProject_UserView.ProjectName,
    dbo.MSP_EpmTask_UserView.TaskName,
    dbo.MSP_EpmAssignment_UserView.ResourceUID,
    dbo.MSP_EpmResource_UserView.ResourceName,
    dbo.MSP_EpmResource_UserView.ResourceInitials
    INTO #TempTable
    FROM dbo.MSP_EpmAssignment_UserView INNER JOIN
    dbo.MSP_EpmProject_UserView ON dbo.MSP_EpmAssignment_UserView.ProjectUID = dbo.MSP_EpmProject_UserView.ProjectUID INNER JOIN
    dbo.MSP_EpmTask_UserView ON dbo.MSP_EpmAssignment_UserView.TaskUID = dbo.MSP_EpmTask_UserView.TaskUID INNER JOIN
    dbo.MSP_EpmResource_UserView ON dbo.MSP_EpmAssignment_UserView.ResourceUID = dbo.MSP_EpmResource_UserView.ResourceUID
    SELECT
    ProjectUID,
    TaskUID,
    ProjectName,
    TaskName,
    STUFF((
    SELECT ', ' + ResourceInitials
    FROM #TempTable
    WHERE (TaskUID = Results.TaskUID)
    FOR XML PATH (''))
    ,1,2,'') AS ResourceInitialsCombined,
    STUFF((
    SELECT ', ' + ResourceName
    FROM #TempTable
    WHERE (TaskUID = Results.TaskUID)
    FOR XML PATH (''))
    ,1,2,'') AS ResourceNameCombined
    FROM #TempTable Results
    GROUP BY TaskUID,ProjectUID,ProjectName,TaskName
    DROP TABLE #TempTable
    -Prashanth

  • Sql query to get numbers from 0 to 99

    How can we write an sql query to get values from 0 to 99 ... this shouldn't be coming from any table

    Bawer wrote:
    Result: (quickly replied by oracle)
    SQL-Error: ORA-30009 (Not enough memory for connect by - 1GB reserved for oracle on VirtualBox)Oracle version? Takes about 8 seconds on my:
    SQL> select * from v$version
      2  /
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for 32-bit Windows: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    Elapsed: 00:00:00.14
    SQL> select count(*) from (
      2  SELECT LEVEL - 1
      3  FROM DUAL
      4  CONNECT BY LEVEL <= 10000000
      5  )
      6  /
      COUNT(*)
      10000000
    Elapsed: 00:00:07.76
    SQL> SY.

  • SQL query to get last 6 months records neglect the current month

    Hi All;
    I need help with 
    sql query to get last 6 months records neglect the current month
    Any help much appreciated
    Thanks
    Pradnya07

    SELECT <> FROM tbl WHERE dt >=dateadd(month,-6,GETDATE())
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Need a sql query to get multiple dates in rows

    Hi All,
    i need a query to get dates for last 7 days and each dates should be in one row...
    but select sysdate from dual..gives one row...
    Expexcted Output
    Dates:
    01-oct-2013
    30-sep-2013
    29-sep-2013
    28-sep-2013
    27-sep-2013
    26-sep-2013

    Hi,
    Do you mean that you want all 7 dates together on 1 row?
    Here's one way:
    SELECT LISTAGG ( TO_CHAR ( SYSDATE + 1 - LEVEL
                              , 'DD-Mon-YYYY'
                    ) WITHIN GROUP (ORDER BY LEVEL)    AS txt
    FROM    dual
    CONNECT BY LEVEL <= 7
    This is an example of String Aggregation, that is, taking a column on multiple rows, and concatenating all the values (however many htere happen to be) into 1 big string column 1 row.
    Like everything else, exactly how to do it depends on your Oracle version.
    For more on String Aggregation, including differetn techniques for different versions, see http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
    Message was edited by: FrankKulash
    Sorry, I mis-read the question.

  • Sql query to get df -h output

    Hi,
    Please provide me sql query to get df -h output. I don't have server (Solaris) access to get df -h output.
    I want to check the space availability on the mount point to increase space at the tablespace level.
    Thank you..

    sb92075 wrote:
    SQL> host df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/sda1             220G   66G  144G  32% /
    none                  1.9G  308K  1.9G   1% /dev
    none                  1.9G  959M  896M  52% /dev/shm
    none                  1.9G   96K  1.9G   1% /var/run
    none                  1.9G     0  1.9G   0% /var/lock
    none                  1.9G     0  1.9G   0% /lib/init/rw
    The "host" command executes on the client machine running sqlplus, not the server that the OP says he doesn't have access to.

  • Dashboard Prompt - Getting error for Adding SQL query in "Default to"

    Hello Oracle,
    I am facing some problem in Dashboard Prompt. Like when i add some sql query in "Default to" in Dashboard prompt and for the next prompt when i check for Contrain option i get error in the second prompt. but it works fine when i hard-code a value in "Default to" options.
    For Example:
    Like when we consider a two prompts :
    1) Year -> (In Default to i select SQL Query and enter the query as SELECT "YTD Dim"."Fiscal Year" FROM "YTD Report" WHERE "YTD Dim"."Fiscal Year" = Year(Current_Date)
    2) Business Unit -> (In specific value i give as some hard code value of Business Unit and check the contrain option)
    i get error as
    Business Unit
    Error Generating Drop Down Values
    A numeric value was expected (received "SELECT "YTD Dim"."Fiscal Year" FROM "YTD Report" WHERE "YTD Dim"."Fiscal Year" = Year(Current_Date)"). Error Details
    Error Codes: EHWH2A7E
    but i get correct value for Year as 2011.
    I need to use SQL query in default to option and need to check the constrain option too.
    Looking for positive feedback.

    You need to create a dashboard prompt and in Default To -> select SQL Results
    Click on the ... (three dots ) underneath it and put in your sql
    For Example , I have a Table called "Sales Date" in my "ABC" presentation folder. This has a column called "Year" and "Date". If I want to have a Year prompt with the default value set to current year, here is what the syntax of my sql result will be :-
    SELECT "ABC"."Sales Date".YEAR
    FROM "ABC"
    WHERE "Date" = current_date
    In SQL, we cannot put SQL as we know of in terms of Oracle, Sql Server etc. The SQL here refers to sql as OBIEE understands it and should be in the form of Select "Presentation foler"."Table Name".ColumnName from "Presentation Folder"
    Hope this helps

  • Query to get the last added record in a table for a particular id

    T
    Hi,
    I have 2 tables A, B
    Table A has id,name
    Table B had parentid(foreignkey referring to ID in above table), record_type,created_timestamp
    I want to get the last added record_type from Table B for all the ids present in Table A.

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. I know this is
    a skeleton, but could you at least try to do good programming? Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. And sample data also helps. 
    I have 2 tables: Alphas, Betas
    CREATE TABLE Alphas
    (alpha_id CHAR(10) NOT NULL PRIMARY KEY,
     alpha_name VARCHAR(25) NOT NULL);
    Why was that DDL so hard you could not write it? But your narrative about the second table does not tell us if it has a key. I will guess that it is also alpha_id, but thanks to your rudeness, that is all we can do. 
    CREATE TABLE Beta 
    (alpha_id CHAR(10) NOT NULL PRIMARY KEY
       REFERENCES Alphas (alpha_id),
     record_type CHAR(2) NOT NULL,
     creation_timestamp DATETIME2(0) DEFAULT CURRENT_TIMESTAMP
          NOT NULL,
    >> I want to get the last added record_type from Table Beta for all the ids present in Table A.<<
    Think about this. Since Beta.alpha_id is a FOREIGN KEY to Alphas, all of its rows will have a match to Alpha. The SQL engine does this for you! 
    SELECT *
    FROM (SELECT alpha_id, record_type, creation_date,
                  MAX(creation_date) OVER () AS creation_date_max
            FROM Betas)
    WHERE creation_date = creation_date_max;
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

Maybe you are looking for

  • How do I assign (or change) the category for a book?

    I can't find a way in Mavericks iBooks (or on my iPad for that matter) to assign categories to books. It used to be simple to do so on my Mac in old pre-iBooks iTunes.  I look to keep my collections subdivided intio categories (e.g I have history sub

  • Canon 1D MkIV images too dark

    Hi there Having a problem here. The RAW images from my Canon 1D Mark IV come in a stop too dark! When I open them, they lookfine; a second later they switch to a too-dark version. I am using Camera Standard, and no other adjustments. It's not just vi

  • User status or user exit

    Dear Gurus, My client requirement is              If my production order status is MSPT(Material shortage),CNF and PCNF should not be possible.Please suggest If any body come accross this situation with user exit or user status please forward the sol

  • HELP!!! Aperture can't find original files!

    Help!!! I imported a 64 Gig SD Card into Aperture for an engagement shoot. It imported the files, about 2,000 CR2 files.  I had to clear the SD card to do another shoot.  When I returned to Aperture, it shows a thumbnail of the file, but yellow excla

  • Warning after update to 10.10.3

    When I rebooted after installing this latest update, a warning was given about an incompatible Rapport Preferences Pane (I believe but cannot remember the exact wording). I found the reference and deleted it. I have had problems with the Trusteer Rap