Merge using schema.subquery

there is a tiny error in the syntax illustration of the merge syntax
Oracle® Database SQL Reference
10g Release 2 (10.2)
Part Number B14200-02
MERGE
Description of the illustration merge.gif
http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/img/merge.gif
MERGE [ hint ]
   INTO [ schema. ] { table | view } [ t_alias ]
   USING [ schema. ] { table | view | subquery }
     [ t_alias ]
   ON ( condition )
   [ merge_update_clause ]
   [ merge_insert_clause ]
   [ error_logging_clause ] ;schema.subquery is of course invalid, so I may suggest
USING {  { [ schema. ] { table | view } } | subquery }
[ t_alias ]
Regards
Laurent

Hi Diana,
Thanks a lot for your answer. Actually, I think you should use
USING dml_table_expression_clause [ alias ]as for insert
DML_table_expression_clause.gif
SQL>
SQL> merge into t1 using t2 partition (p1)
  2  on (t1.x=t2.x)
  3  when not matched then
  4    insert values(t2.x);
0 rows merged.
SQL>
SQL> merge into t1 using t2 subpartition (p11)
  2  on (t1.x=t2.x)
  3  when not matched then
  4    insert values(t2.x);
0 rows merged.
SQL>
SQL> merge into t1 using table(f)
  2  on (t1.x=column_value)
  3  when not matched then
  4    insert values(column_value);
1 row merged.and review the text description of DML_TABLE_EXPRESSION clause
http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/img_text/DML_table_expression_clause.htm
... because it is not very accurate
{ [ schema. ]
  { table
    [ { PARTITION (partition)
      | SUBPARTITION (subpartition)
    | @ dblink
  | { view | materialized view } [ @ dblink ]
| ( subquery [ subquery_restriction_clause ] )
| table_collection_expression
}should be
{ [ schema. ]
  table
      { PARTITION (partition)
        | SUBPARTITION (subpartition)
      | @ dblink
  | { view | materialized view } [ @ dblink ]
| ( subquery [ subquery_restriction_clause ] )
|  table_collection_expression

Similar Messages

  • How do you join two tables from different Oracle schemas using a subquery

    I am trying to join two tables from different Oracle schemas using a subquery. I can extract data from each of the tables without a problem. However, when I combine the select statements using a subquery I get the Oracle error *'ORA-00936: missing expression'*. Since each SELECT statement executes on its own without error I don't understand what is missing. The result set I am trying to get is to match up the LINE_ID from PDTABLE_12_1 in schema DD_12809 with the MAT_DESCRIPTION from table PDTABLE_201 in schema RA_12809.
    The query is as follows:
    sql = "SELECT [DD_12809].[PDTABLE_12_1].LINE_ID FROM [DD_12809].[PDTABLE_12_1] JOIN " _
    + "(SELECT [RA_12809].[PDTABLE_201].MAT_DESCRIPTION " _
    + "FROM [RA_12809].[PDTABLE_201]) AS FAB " _
    + "ON [DD_12809].[PDTABLE_12_1].PIPING_MATER_CLASS = FAB.PIPING_MATER_CLASS"
    The format of the query is copied from a SQL programming manual.
    I also tried executing the query using a straight JOIN on the two tables but got the same results. Any insight would be helpful. Thanks!
    Edited by: user11338343 on Oct 19, 2009 6:55 AM

    I believe you are receiving the error because you are trying to JOIN on a column that doesn't exist. For example you are trying to join on FAB.PIPING_MATER_CLASS but that column does not exist in the subquery.
    If you want to do a straight join without a subquery you could do the following
    SELECT  DD_12809.PDTABLE_12_1.LINE_ID
    ,       FAB.MAT_DESCRIPTION
    FROM    DD_12809.PDTABLE_12_1
    JOIN    RA_12809.PDTABLE_201    AS FAB ON DD_12809.PDTABLE_12_1.PIPING_MATER_CLASS = FAB.PIPING_MATER_CLASS  HTH!

  • Using a SUBQUERY? Does it  have a limit?

    I am using a subquery :
    Select id_book from BOOK
    where id_book in (Select id_book_tt from TEMPTABLE)
    and id_book_type = 'B'
    TEMPTABLE will return 800 id_book_tt
    Now,how many values can the 'WHERE id_book in' clause hold that are returned back
    from the SUBQUERY? Is the MAX LIMIT 255?
    Is there a better way to do it?
                   

    Hi,
    TEST> select count(object_id) from dba_objects;
    COUNT(OBJECT_ID)
                9495
    TEST> select count(*) from dba_objects
      2  where object_id in (select object_id from dba_objects)
      3* and object_type='TABLE';
      COUNT(*)
          1341The 255 limit applies only when you explicitely list the elements ( where a in (1,2,3,4,5,...) ).
    A better way? Well, it depends on your data model... without knowing what you're trying to acieve, the schema setup, etc it's impossible to give advices.
    Regards,
    Yoann.

  • Can you use schema name in "INTO TABLE" in sqlldr?

    Hi All,
    I have a simple question.
    My Oracle userid is SBHAT.
    SBHAT has insert,delete, select,update privileges on a Table in another schema XYZ.
    I want to SQL*Load data in Table EMPLOYEE in XYZ schema, using my userid. Something like ....
    sqlldr userid=*SBHAT*/password control=test.ctl data=test.txt
    I tried to use the following in my test.ctl file but it does not work.
    load data
    append
    into table "XYZ.EMPLOYEE"
    fields terminated by ',' optionally enclosed by '"'
    trailing nullcols
    Can someone give me the proper syntax for into table that uses *schema.table_name* construct.
    Thanks,
    Suresh

    Pl post exact OS and database versions - what do you get when you execute sql*loader with the syntax you have identified so far ?
    http://docs.oracle.com/cd/E11882_01/server.112/e22490/ldr_control_file.htm#i1005623
    HTH
    Srini

  • Top n Analysis using correlated subquery

    Please explain this query. It is doing top n analysis using correlated subquery. I need explaination of execution of this query.
    Select distinct a.sal
    From emp a
    where 1=(select count ( distinct b.sal) from emp b
         where a.sal <=b.sal)
    Thanks in advance

    Try breaking the query down and rewriting it in order to follow the logic;
    SQL> --
    SQL> -- Start by getting each salary from emp along with a count of all salaries in emp
    SQL> --
    SQL> select   a.sal,
            (select count (distinct b.sal) from scott.emp b ) count_sal
    from scott.emp a
    order by 1 desc
           SAL  COUNT_SAL
          5000         12
          3000         12
          3000         12
          2975         12
          2850         12
          2450         12
          1600         12
          1500         12
          1300         12
          1250         12
          1250         12
          1100         12
           950         12
           800         12
    14 rows selected.
    SQL> --
    SQL> --Add a condition to the count for only salaries below or equal to the current salarySQL> --
    SQL> select   a.sal,
            (select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) rank_sal
    from scott.emp a
    order by 1 desc
           SAL   RANK_SAL
          5000          1
          3000          2
          3000          2
          2975          3
          2850          4
          2450          5
          1600          6
          1500          7
          1300          8
          1250          9
          1250          9
          1100         10
           950         11
           800         12
    14 rows selected.
    SQL> --
    SQL> -- Add a condition to only pick the nth highest salary
    SQL> --
    SQL> select    a.sal,
             (select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) rank_sal
    from scott.emp a
    where (select count (distinct b.sal) from scott.emp b where a.sal <=b.sal) = 4
           SAL   RANK_SAL
          2850          4
    1 row selected.Hope this helps.

  • Past usedMAIL MERGE using DDE - Anyone know any of the following questions?

    Hi All,
    Years ago I had called MS Word through DDE, Dynamic Data Exchange, old technology, and created form letter passing address info from the database.
    I used PowerBuilder to:
    1. Open MS Word
    2. Call Mail Merge with a template name (which had the tags to replace)
    3. Passing the results of a query
    Oh ya... we need HTMLDB to call MS Word on the client...
    1. ) Anyone know how to bring up MS WORD - (Not Word Pad) on the client?
    2.) Word had an interface, DDE, to send commands to Word.
    I think I'm remembering correctly..
    I'm going to did a bit but it will take time to get to it so I was hoping to get a head start by someone's experience and have a few KEY words to search on??
    Thanks, Bill
    Message was edited by:
    bcarlis_2000
    Message was edited by:
    bcarlis_2000

    Hi Bill,
    My Team uses MSWord mail merge with a 2 step process:
    One: Build a report that contains the data you need for the Mail Merge and then export it to a CSV file.
    Two: Export the mail merge template (which is stored in a BLOB) to the same directory as the CSV file. The template is set up to use the CSV file as its datasource.
    It's a bit clunky but our users seem content with it.
    Another alternative would be to search this forum for "Mail Merge". One posting (a year ago) shows how to do a mail merge using an RTF file in one step (after importing the RTF template into your APEX application). The only downside was that the RTF file has a 30K size limit (not a problem if you do not have to include a graphic like a logo).
    By the way, I used to control the MS Mail Merge process directly from within VB6. The two step process above seems like a bit of a step backwards but it works.
    Hope this helps.
    Cheers
    Patrick Cimolini

  • I have created a merged letter (mail merge) using Word for Mac. But I cannot merge the letter to my contacts which are in the Apple Mail Application. Is it possible to do this?

    I have created a merged letter (mail merge) using Word for Mac. But I cannot merge the letter to my contacts which are in the Apple Mail Application. Is it possible to do this?
    Word for Mac 8
    i mac intel

    This is the Apple Keynote discussion, you should post in the Microsoft forums where the experts there can help you, there is a dedicated mailmarge discussion here:    Microsoft Office Word Mailmerge

  • Validating xml doc using schema

    I was wondering if you can the following validation of an xml document using schema:
    <parent>
        <child>Jogn</child>
        <child>Hanna</child>
        <child>Blake</child>
        <childCount>3</childCount>
    <parent>the childcountValue equals the number of child node. is this possible using
    schema or do do i have to use an application to do this?
    thanx in advance

    thanx dvohra, but i already know how to validate schema using a parser.
    I'm looking for a way in the schema that specified thhat the total number of child elemnt equals to the integer value of the childTotal element. I don't even know if this is possible. If possible, what (tag) would i use. i don't need answer..hint would be nice.
    my other solution is to write an application that use a SAX parser to parse the xml doc. Although this is relatively easy, i would like to keep the validation within on file (the schema)..rather than have it be in the schema and a ContentHandler.

  • Can you use a subquery when importing from a file?

    I was wondering if the DBMS_DATAPUMP API allows using a subquery (DATA_FILTER) when executing an import from a file?
    I am unable of limiting my data when creating the export file because my subquery requires a database link, which is not an option on the server I'm working on. So I'm wondering if I can limit my data on the import from a file, rather than the export?
    Thanks for any advice...
    ivalum21

    I was wondering if the DBMS_DATAPUMP API allows using a subquery (DATA_FILTER) when executing an import from a file?From the documentation I would say yes:
    SUBQUERY:
    Specifies a subquery that is added to the end of the SELECT statement for the table. If you specify a WHERE clause in the subquery, you can restrict the rows that are selected. Specifying an ORDER BY clause orders the rows dumped in the export which improves performance when migrating from heap-organized tables to index-organized tables.
    «

  • OPEN SQL - use of subquery to get max date

    Hello,
    I am trying to use a subquery to get the latest record, but cannot get the syntax correct.
    select single from hrp1001 into mydata
    where objid = '122334'
    where begda  = ( select max ( begda ) from hrp1001 where objid  = '122334' )
    but cannot get it right.
    I am just trying to get the record with the max(date).
    Thanks

    Hello,
    To get a better performance, I suggest you the following:
    select single * from hrp1001 into corresponding fields of mydata
    where objid = '122334'
    order by begda descending.
    Regards,

  • Is it possible to do an email merge using Excel on my iMac? If so, how?

    I'm hoping someone can help me. I'm working off of an Excel doc and my client has asked me to send a personalized email to 300+ people. I'm wondering if it's possible to do a mail merge. I have a iMac OS X Version 10.6.8.  Any help would be greatly appreciated.

    To do a mail merge using office, you would need to configure outlook.
    Will you be using your gmail address? if so, How To Wrangle Outlook 2011 To Work With Gmail explains how to setup outlook to use a gmail email address.
    If not, what domain will you be sending your mailing outwith? (that's the part after the name ie @gmail.com, @yahoo.com, @facebook.com, extra)
    After you setup Outlook. You might want to check out Use Mail Merge to create a form letter. While the instructions While it's not specific to an email address. But it dose explain the the basics of mail merge process.

  • How do I know I am using schema 2?

    I just installed JCS2005Q4 Windows on Windows Server 2003.
    I selected the "automatically configure" option.
    I am now unsure as to the following
    1 Am I using schema 2 by default? How can I check? Is there some telltale file or signature?
    2 Should I run comm_dssetup.pl after setup completed.
    Messaging Server seems to be running fine and the initial users are able to mail eachother. Do I understand it correctly that when selecting "automatically configure" that the comm_dssetup.pl and other scripts are automatically run for me and I am ready to go?

    Did you install Access Manager?
    Did you install Delegated Admin? Does it work?
    If "yes" to above, you're on schema 2
    If your messaging server is up and running, then comm_dssetup.pl was run for you already.
    How did you configure 'initial users"?

  • Sliding Window Table Partitioning Problems with RANGE RIGHT, SPLIT, MERGE using Multiple File Groups

    There is misleading information in two system views (sys.data_spaces & sys.destination_data_spaces) about the physical location of data after a partitioning MERGE and before an INDEX REBUILD operation on a partitioned table. In SQL Server 2012 SP1 CU6,
    the script below (SQLCMD mode, set DataDrive  & LogDrive variables  for the runtime environment) will create a test database with file groups and files to support a partitioned table. The partition function and scheme spread the test data across
    4 files groups, an empty partition, file group and file are maintained at the start and end of the range. A problem occurs after the SWITCH and MERGE RANGE operations, the views sys.data_spaces & sys.destination_data_spaces show the logical, not the physical,
    location of data.
    --=================================================================================
    -- PartitionLabSetup_RangeRight.sql
    -- 001. Create test database
    -- 002. Add file groups and files
    -- 003. Create partition function and schema
    -- 004. Create and populate a test table
    --=================================================================================
    USE [master]
    GO
    -- 001 - Create Test Database
    :SETVAR DataDrive "D:\SQL\Data\"
    :SETVAR LogDrive "D:\SQL\Logs\"
    :SETVAR DatabaseName "workspace"
    :SETVAR TableName "TestTable"
    -- Drop if exists and create Database
    IF DATABASEPROPERTYEX(N'$(databasename)','Status') IS NOT NULL
    BEGIN
    ALTER DATABASE $(DatabaseName) SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    DROP DATABASE $(DatabaseName)
    END
    CREATE DATABASE $(DatabaseName)
    ON
    ( NAME = $(DatabaseName)_data,
    FILENAME = N'$(DataDrive)$(DatabaseName)_data.mdf',
    SIZE = 10,
    MAXSIZE = 500,
    FILEGROWTH = 5 )
    LOG ON
    ( NAME = $(DatabaseName)_log,
    FILENAME = N'$(LogDrive)$(DatabaseName).ldf',
    SIZE = 5MB,
    MAXSIZE = 5000MB,
    FILEGROWTH = 5MB ) ;
    GO
    -- 002. Add file groups and files
    --:SETVAR DatabaseName "workspace"
    --:SETVAR TableName "TestTable"
    --:SETVAR DataDrive "D:\SQL\Data\"
    --:SETVAR LogDrive "D:\SQL\Logs\"
    DECLARE @nSQL NVARCHAR(2000) ;
    DECLARE @x INT = 1;
    WHILE @x <= 6
    BEGIN
    SELECT @nSQL =
    'ALTER DATABASE $(DatabaseName)
    ADD FILEGROUP $(TableName)_fg' + RTRIM(CAST(@x AS CHAR(5))) + ';
    ALTER DATABASE $(DatabaseName)
    ADD FILE
    NAME= ''$(TableName)_f' + CAST(@x AS CHAR(5)) + ''',
    FILENAME = ''$(DataDrive)\$(TableName)_f' + RTRIM(CAST(@x AS CHAR(5))) + '.ndf''
    TO FILEGROUP $(TableName)_fg' + RTRIM(CAST(@x AS CHAR(5))) + ';'
    EXEC sp_executeSQL @nSQL;
    SET @x = @x + 1;
    END
    -- 003. Create partition function and schema
    --:SETVAR TableName "TestTable"
    --:SETVAR DatabaseName "workspace"
    USE $(DatabaseName);
    CREATE PARTITION FUNCTION $(TableName)_func (int)
    AS RANGE RIGHT FOR VALUES
    0,
    15,
    30,
    45,
    60
    CREATE PARTITION SCHEME $(TableName)_scheme
    AS
    PARTITION $(TableName)_func
    TO
    $(TableName)_fg1,
    $(TableName)_fg2,
    $(TableName)_fg3,
    $(TableName)_fg4,
    $(TableName)_fg5,
    $(TableName)_fg6
    -- Create TestTable
    --:SETVAR TableName "TestTable"
    --:SETVAR BackupDrive "D:\SQL\Backups\"
    --:SETVAR DatabaseName "workspace"
    CREATE TABLE [dbo].$(TableName)(
    [Partition_PK] [int] NOT NULL,
    [GUID_PK] [uniqueidentifier] NOT NULL,
    [CreateDate] [datetime] NULL,
    [CreateServer] [nvarchar](50) NULL,
    [RandomNbr] [int] NULL,
    CONSTRAINT [PK_$(TableName)] PRIMARY KEY CLUSTERED
    [Partition_PK] ASC,
    [GUID_PK] ASC
    ) ON $(TableName)_scheme(Partition_PK)
    ) ON $(TableName)_scheme(Partition_PK)
    ALTER TABLE [dbo].$(TableName) ADD CONSTRAINT [DF_$(TableName)_GUID_PK] DEFAULT (newid()) FOR [GUID_PK]
    ALTER TABLE [dbo].$(TableName) ADD CONSTRAINT [DF_$(TableName)_CreateDate] DEFAULT (getdate()) FOR [CreateDate]
    ALTER TABLE [dbo].$(TableName) ADD CONSTRAINT [DF_$(TableName)_CreateServer] DEFAULT (@@servername) FOR [CreateServer]
    -- 004. Create and populate a test table
    -- Load TestTable Data - Seconds 0-59 are used as the Partitoning Key
    --:SETVAR TableName "TestTable"
    SET NOCOUNT ON;
    DECLARE @Now DATETIME = GETDATE()
    WHILE @Now > DATEADD(minute,-1,GETDATE())
    BEGIN
    INSERT INTO [dbo].$(TableName)
    ([Partition_PK]
    ,[RandomNbr])
    VALUES
    DATEPART(second,GETDATE())
    ,ROUND((RAND() * 100),0)
    END
    -- Confirm table partitioning - http://lextonr.wordpress.com/tag/sys-destination_data_spaces/
    SELECT
    N'DatabaseName' = DB_NAME()
    , N'SchemaName' = s.name
    , N'TableName' = o.name
    , N'IndexName' = i.name
    , N'IndexType' = i.type_desc
    , N'PartitionScheme' = ps.name
    , N'DataSpaceName' = ds.name
    , N'DataSpaceType' = ds.type_desc
    , N'PartitionFunction' = pf.name
    , N'PartitionNumber' = dds.destination_id
    , N'BoundaryValue' = prv.value
    , N'RightBoundary' = pf.boundary_value_on_right
    , N'PartitionFileGroup' = ds2.name
    , N'RowsOfData' = p.[rows]
    FROM
    sys.objects AS o
    INNER JOIN sys.schemas AS s
    ON o.[schema_id] = s.[schema_id]
    INNER JOIN sys.partitions AS p
    ON o.[object_id] = p.[object_id]
    INNER JOIN sys.indexes AS i
    ON p.[object_id] = i.[object_id]
    AND p.index_id = i.index_id
    INNER JOIN sys.data_spaces AS ds
    ON i.data_space_id = ds.data_space_id
    INNER JOIN sys.partition_schemes AS ps
    ON ds.data_space_id = ps.data_space_id
    INNER JOIN sys.partition_functions AS pf
    ON ps.function_id = pf.function_id
    LEFT OUTER JOIN sys.partition_range_values AS prv
    ON pf.function_id = prv.function_id
    AND p.partition_number = prv.boundary_id
    LEFT OUTER JOIN sys.destination_data_spaces AS dds
    ON ps.data_space_id = dds.partition_scheme_id
    AND p.partition_number = dds.destination_id
    LEFT OUTER JOIN sys.data_spaces AS ds2
    ON dds.data_space_id = ds2.data_space_id
    ORDER BY
    DatabaseName
    ,SchemaName
    ,TableName
    ,IndexName
    ,PartitionNumber
    --=================================================================================
    -- SECTION 2 - SWITCH OUT
    -- 001 - Create TestTableOut
    -- 002 - Switch out partition in range 0-14
    -- 003 - Merge range 0 -29
    -- 001. TestTableOut
    :SETVAR TableName "TestTable"
    IF OBJECT_ID('dbo.$(TableName)Out') IS NOT NULL
    DROP TABLE [dbo].[$(TableName)Out]
    CREATE TABLE [dbo].[$(TableName)Out](
    [Partition_PK] [int] NOT NULL,
    [GUID_PK] [uniqueidentifier] NOT NULL,
    [CreateDate] [datetime] NULL,
    [CreateServer] [nvarchar](50) NULL,
    [RandomNbr] [int] NULL,
    CONSTRAINT [PK_$(TableName)Out] PRIMARY KEY CLUSTERED
    [Partition_PK] ASC,
    [GUID_PK] ASC
    ) ON $(TableName)_fg2;
    GO
    -- 002 - Switch out partition in range 0-14
    --:SETVAR TableName "TestTable"
    ALTER TABLE dbo.$(TableName)
    SWITCH PARTITION 2 TO dbo.$(TableName)Out;
    -- 003 - Merge range 0 - 29
    --:SETVAR TableName "TestTable"
    ALTER PARTITION FUNCTION $(TableName)_func()
    MERGE RANGE (15);
    -- Confirm table partitioning
    -- Original source of this query - http://lextonr.wordpress.com/tag/sys-destination_data_spaces/
    SELECT
    N'DatabaseName' = DB_NAME()
    , N'SchemaName' = s.name
    , N'TableName' = o.name
    , N'IndexName' = i.name
    , N'IndexType' = i.type_desc
    , N'PartitionScheme' = ps.name
    , N'DataSpaceName' = ds.name
    , N'DataSpaceType' = ds.type_desc
    , N'PartitionFunction' = pf.name
    , N'PartitionNumber' = dds.destination_id
    , N'BoundaryValue' = prv.value
    , N'RightBoundary' = pf.boundary_value_on_right
    , N'PartitionFileGroup' = ds2.name
    , N'RowsOfData' = p.[rows]
    FROM
    sys.objects AS o
    INNER JOIN sys.schemas AS s
    ON o.[schema_id] = s.[schema_id]
    INNER JOIN sys.partitions AS p
    ON o.[object_id] = p.[object_id]
    INNER JOIN sys.indexes AS i
    ON p.[object_id] = i.[object_id]
    AND p.index_id = i.index_id
    INNER JOIN sys.data_spaces AS ds
    ON i.data_space_id = ds.data_space_id
    INNER JOIN sys.partition_schemes AS ps
    ON ds.data_space_id = ps.data_space_id
    INNER JOIN sys.partition_functions AS pf
    ON ps.function_id = pf.function_id
    LEFT OUTER JOIN sys.partition_range_values AS prv
    ON pf.function_id = prv.function_id
    AND p.partition_number = prv.boundary_id
    LEFT OUTER JOIN sys.destination_data_spaces AS dds
    ON ps.data_space_id = dds.partition_scheme_id
    AND p.partition_number = dds.destination_id
    LEFT OUTER JOIN sys.data_spaces AS ds2
    ON dds.data_space_id = ds2.data_space_id
    ORDER BY
    DatabaseName
    ,SchemaName
    ,TableName
    ,IndexName
    ,PartitionNumber  
    The table below shows the results of the ‘Confirm Table Partitioning’ query, before and after the MERGE.
    The T-SQL code below illustrates the problem.
    -- PartitionLab_RangeRight
    USE workspace;
    DROP TABLE dbo.TestTableOut;
    USE master;
    ALTER DATABASE workspace
    REMOVE FILE TestTable_f3 ;
    -- ERROR
    --Msg 5042, Level 16, State 1, Line 1
    --The file 'TestTable_f3 ' cannot be removed because it is not empty.
    ALTER DATABASE workspace
    REMOVE FILE TestTable_f2 ;
    -- Works surprisingly!!
    use workspace;
    ALTER INDEX [PK_TestTable] ON [dbo].[TestTable] REBUILD PARTITION = 2;
    --Msg 622, Level 16, State 3, Line 2
    --The filegroup "TestTable_fg2" has no files assigned to it. Tables, indexes, text columns, ntext columns, and image columns cannot be populated on this filegroup until a file is added.
    --The statement has been terminated.
    If you run ALTER INDEX REBUILD before trying to remove files from File Group 3, it works. Rerun the database setup script then the code below.
    -- RANGE RIGHT
    -- Rerun PartitionLabSetup_RangeRight.sql before the code below
    USE workspace;
    DROP TABLE dbo.TestTableOut;
    ALTER INDEX [PK_TestTable] ON [dbo].[TestTable] REBUILD PARTITION = 2;
    USE master;
    ALTER DATABASE workspace
    REMOVE FILE TestTable_f3;
    -- Works as expected!!
    The file in File Group 2 appears to contain data but it can be dropped. Although the system views are reporting the data in File Group 2, it still physically resides in File Group 3 and isn’t moved until the index is rebuilt. The RANGE RIGHT function means
    the left file group (File Group 2) is retained when splitting ranges.
    RANGE LEFT would have retained the data in File Group 3 where it already resided, no INDEX REBUILD is necessary to effectively complete the MERGE operation. The script below implements the same partitioning strategy (data distribution between partitions)
    on the test table but uses different boundary definitions and RANGE LEFT.
    --=================================================================================
    -- PartitionLabSetup_RangeLeft.sql
    -- 001. Create test database
    -- 002. Add file groups and files
    -- 003. Create partition function and schema
    -- 004. Create and populate a test table
    --=================================================================================
    USE [master]
    GO
    -- 001 - Create Test Database
    :SETVAR DataDrive "D:\SQL\Data\"
    :SETVAR LogDrive "D:\SQL\Logs\"
    :SETVAR DatabaseName "workspace"
    :SETVAR TableName "TestTable"
    -- Drop if exists and create Database
    IF DATABASEPROPERTYEX(N'$(databasename)','Status') IS NOT NULL
    BEGIN
    ALTER DATABASE $(DatabaseName) SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    DROP DATABASE $(DatabaseName)
    END
    CREATE DATABASE $(DatabaseName)
    ON
    ( NAME = $(DatabaseName)_data,
    FILENAME = N'$(DataDrive)$(DatabaseName)_data.mdf',
    SIZE = 10,
    MAXSIZE = 500,
    FILEGROWTH = 5 )
    LOG ON
    ( NAME = $(DatabaseName)_log,
    FILENAME = N'$(LogDrive)$(DatabaseName).ldf',
    SIZE = 5MB,
    MAXSIZE = 5000MB,
    FILEGROWTH = 5MB ) ;
    GO
    -- 002. Add file groups and files
    --:SETVAR DatabaseName "workspace"
    --:SETVAR TableName "TestTable"
    --:SETVAR DataDrive "D:\SQL\Data\"
    --:SETVAR LogDrive "D:\SQL\Logs\"
    DECLARE @nSQL NVARCHAR(2000) ;
    DECLARE @x INT = 1;
    WHILE @x <= 6
    BEGIN
    SELECT @nSQL =
    'ALTER DATABASE $(DatabaseName)
    ADD FILEGROUP $(TableName)_fg' + RTRIM(CAST(@x AS CHAR(5))) + ';
    ALTER DATABASE $(DatabaseName)
    ADD FILE
    NAME= ''$(TableName)_f' + CAST(@x AS CHAR(5)) + ''',
    FILENAME = ''$(DataDrive)\$(TableName)_f' + RTRIM(CAST(@x AS CHAR(5))) + '.ndf''
    TO FILEGROUP $(TableName)_fg' + RTRIM(CAST(@x AS CHAR(5))) + ';'
    EXEC sp_executeSQL @nSQL;
    SET @x = @x + 1;
    END
    -- 003. Create partition function and schema
    --:SETVAR TableName "TestTable"
    --:SETVAR DatabaseName "workspace"
    USE $(DatabaseName);
    CREATE PARTITION FUNCTION $(TableName)_func (int)
    AS RANGE LEFT FOR VALUES
    -1,
    14,
    29,
    44,
    59
    CREATE PARTITION SCHEME $(TableName)_scheme
    AS
    PARTITION $(TableName)_func
    TO
    $(TableName)_fg1,
    $(TableName)_fg2,
    $(TableName)_fg3,
    $(TableName)_fg4,
    $(TableName)_fg5,
    $(TableName)_fg6
    -- Create TestTable
    --:SETVAR TableName "TestTable"
    --:SETVAR BackupDrive "D:\SQL\Backups\"
    --:SETVAR DatabaseName "workspace"
    CREATE TABLE [dbo].$(TableName)(
    [Partition_PK] [int] NOT NULL,
    [GUID_PK] [uniqueidentifier] NOT NULL,
    [CreateDate] [datetime] NULL,
    [CreateServer] [nvarchar](50) NULL,
    [RandomNbr] [int] NULL,
    CONSTRAINT [PK_$(TableName)] PRIMARY KEY CLUSTERED
    [Partition_PK] ASC,
    [GUID_PK] ASC
    ) ON $(TableName)_scheme(Partition_PK)
    ) ON $(TableName)_scheme(Partition_PK)
    ALTER TABLE [dbo].$(TableName) ADD CONSTRAINT [DF_$(TableName)_GUID_PK] DEFAULT (newid()) FOR [GUID_PK]
    ALTER TABLE [dbo].$(TableName) ADD CONSTRAINT [DF_$(TableName)_CreateDate] DEFAULT (getdate()) FOR [CreateDate]
    ALTER TABLE [dbo].$(TableName) ADD CONSTRAINT [DF_$(TableName)_CreateServer] DEFAULT (@@servername) FOR [CreateServer]
    -- 004. Create and populate a test table
    -- Load TestTable Data - Seconds 0-59 are used as the Partitoning Key
    --:SETVAR TableName "TestTable"
    SET NOCOUNT ON;
    DECLARE @Now DATETIME = GETDATE()
    WHILE @Now > DATEADD(minute,-1,GETDATE())
    BEGIN
    INSERT INTO [dbo].$(TableName)
    ([Partition_PK]
    ,[RandomNbr])
    VALUES
    DATEPART(second,GETDATE())
    ,ROUND((RAND() * 100),0)
    END
    -- Confirm table partitioning - http://lextonr.wordpress.com/tag/sys-destination_data_spaces/
    SELECT
    N'DatabaseName' = DB_NAME()
    , N'SchemaName' = s.name
    , N'TableName' = o.name
    , N'IndexName' = i.name
    , N'IndexType' = i.type_desc
    , N'PartitionScheme' = ps.name
    , N'DataSpaceName' = ds.name
    , N'DataSpaceType' = ds.type_desc
    , N'PartitionFunction' = pf.name
    , N'PartitionNumber' = dds.destination_id
    , N'BoundaryValue' = prv.value
    , N'RightBoundary' = pf.boundary_value_on_right
    , N'PartitionFileGroup' = ds2.name
    , N'RowsOfData' = p.[rows]
    FROM
    sys.objects AS o
    INNER JOIN sys.schemas AS s
    ON o.[schema_id] = s.[schema_id]
    INNER JOIN sys.partitions AS p
    ON o.[object_id] = p.[object_id]
    INNER JOIN sys.indexes AS i
    ON p.[object_id] = i.[object_id]
    AND p.index_id = i.index_id
    INNER JOIN sys.data_spaces AS ds
    ON i.data_space_id = ds.data_space_id
    INNER JOIN sys.partition_schemes AS ps
    ON ds.data_space_id = ps.data_space_id
    INNER JOIN sys.partition_functions AS pf
    ON ps.function_id = pf.function_id
    LEFT OUTER JOIN sys.partition_range_values AS prv
    ON pf.function_id = prv.function_id
    AND p.partition_number = prv.boundary_id
    LEFT OUTER JOIN sys.destination_data_spaces AS dds
    ON ps.data_space_id = dds.partition_scheme_id
    AND p.partition_number = dds.destination_id
    LEFT OUTER JOIN sys.data_spaces AS ds2
    ON dds.data_space_id = ds2.data_space_id
    ORDER BY
    DatabaseName
    ,SchemaName
    ,TableName
    ,IndexName
    ,PartitionNumber
    --=================================================================================
    -- SECTION 2 - SWITCH OUT
    -- 001 - Create TestTableOut
    -- 002 - Switch out partition in range 0-14
    -- 003 - Merge range 0 -29
    -- 001. TestTableOut
    :SETVAR TableName "TestTable"
    IF OBJECT_ID('dbo.$(TableName)Out') IS NOT NULL
    DROP TABLE [dbo].[$(TableName)Out]
    CREATE TABLE [dbo].[$(TableName)Out](
    [Partition_PK] [int] NOT NULL,
    [GUID_PK] [uniqueidentifier] NOT NULL,
    [CreateDate] [datetime] NULL,
    [CreateServer] [nvarchar](50) NULL,
    [RandomNbr] [int] NULL,
    CONSTRAINT [PK_$(TableName)Out] PRIMARY KEY CLUSTERED
    [Partition_PK] ASC,
    [GUID_PK] ASC
    ) ON $(TableName)_fg2;
    GO
    -- 002 - Switch out partition in range 0-14
    --:SETVAR TableName "TestTable"
    ALTER TABLE dbo.$(TableName)
    SWITCH PARTITION 2 TO dbo.$(TableName)Out;
    -- 003 - Merge range 0 - 29
    :SETVAR TableName "TestTable"
    ALTER PARTITION FUNCTION $(TableName)_func()
    MERGE RANGE (14);
    -- Confirm table partitioning
    -- Original source of this query - http://lextonr.wordpress.com/tag/sys-destination_data_spaces/
    SELECT
    N'DatabaseName' = DB_NAME()
    , N'SchemaName' = s.name
    , N'TableName' = o.name
    , N'IndexName' = i.name
    , N'IndexType' = i.type_desc
    , N'PartitionScheme' = ps.name
    , N'DataSpaceName' = ds.name
    , N'DataSpaceType' = ds.type_desc
    , N'PartitionFunction' = pf.name
    , N'PartitionNumber' = dds.destination_id
    , N'BoundaryValue' = prv.value
    , N'RightBoundary' = pf.boundary_value_on_right
    , N'PartitionFileGroup' = ds2.name
    , N'RowsOfData' = p.[rows]
    FROM
    sys.objects AS o
    INNER JOIN sys.schemas AS s
    ON o.[schema_id] = s.[schema_id]
    INNER JOIN sys.partitions AS p
    ON o.[object_id] = p.[object_id]
    INNER JOIN sys.indexes AS i
    ON p.[object_id] = i.[object_id]
    AND p.index_id = i.index_id
    INNER JOIN sys.data_spaces AS ds
    ON i.data_space_id = ds.data_space_id
    INNER JOIN sys.partition_schemes AS ps
    ON ds.data_space_id = ps.data_space_id
    INNER JOIN sys.partition_functions AS pf
    ON ps.function_id = pf.function_id
    LEFT OUTER JOIN sys.partition_range_values AS prv
    ON pf.function_id = prv.function_id
    AND p.partition_number = prv.boundary_id
    LEFT OUTER JOIN sys.destination_data_spaces AS dds
    ON ps.data_space_id = dds.partition_scheme_id
    AND p.partition_number = dds.destination_id
    LEFT OUTER JOIN sys.data_spaces AS ds2
    ON dds.data_space_id = ds2.data_space_id
    ORDER BY
    DatabaseName
    ,SchemaName
    ,TableName
    ,IndexName
    ,PartitionNumber
    The table below shows the results of the ‘Confirm Table Partitioning’ query, before and after the MERGE.
    The data in the File and File Group to be dropped (File Group 2) has already been switched out; File Group 3 contains the data so no index rebuild is needed to move data and complete the MERGE.
    RANGE RIGHT would not be a problem in a ‘Sliding Window’ if the same file group is used for all partitions, when they are created and dropped it introduces a dependency on full index rebuilds. Larger tables are typically partitioned and a full index rebuild
    might be an expensive operation. I’m not sure how a RANGE RIGHT partitioning strategy could be implemented, with an ascending partitioning key, using multiple file groups without having to move data. Using a single file group (multiple files) for all partitions
    within a table would avoid physically moving data between file groups; no index rebuild would be necessary to complete a MERGE and system views would accurately reflect the physical location of data. 
    If a RANGE RIGHT partition function is used, the data is physically in the wrong file group after the MERGE assuming a typical ascending partitioning key, and the 'Data Spaces' system views might be misleading. Thanks to Manuj and Chris for a lot of help
    investigating this.
    NOTE 10/03/2014 - The solution
    The solution is so easy it's embarrassing, I was using the wrong boundary points for the MERGE (both RANGE LEFT & RANGE RIGHT) to get rid of historic data.
    -- Wrong Boundary Point Range Right
    --ALTER PARTITION FUNCTION $(TableName)_func()
    --MERGE RANGE (15);
    -- Wrong Boundary Point Range Left
    --ALTER PARTITION FUNCTION $(TableName)_func()
    --MERGE RANGE (14);
    -- Correct Boundary Pounts for MERGE
    ALTER PARTITION FUNCTION $(TableName)_func()
    MERGE RANGE (0); -- or -1 for RANGE LEFT
    The empty, switched out partition (on File Group 2) is then MERGED with the empty partition maintained at the start of the range and no data movement is necessary. I retract the suggestion that a problem exists with RANGE RIGHT Sliding Windows using multiple
    file groups and apologize :-)

    Hi Paul Brewer,
    Thanks for your post and glad to hear that the issue is resolved. It is kind of you post a reply to share your solution. That way, other community members could benefit from your sharing.
    Regards.
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • Merging 5 schema to one schema

    Hi All
    we have 5 company codes & 5 PY Schemas, to avoid user confusion we need to use One schema for all 5 company codes/schemas.
    How we can create a custom schema to merge all , means each schemas will b a sub schema in one main schema,  should ref comapny code
    and execute
    appreciate immediate response
    SK

    Hi ,
    Please find the below logic :
    IF        Z100      Checking the company code 1000 by using SCOND IF = T
    COPY Z101 COPY is function is used for schema within schema , copy from standard or create new
    END IF.       condition is completed
    IF        Z200  Checking the company code 2000 by using SCOND IF = T
    COPY Z201
    ENDIF
    IF        Z300  Checking the company code 3000 by using SCOND IF = T
    COPY Z301
    ENDIF
    IF        Z400  Checking the company code 4000 by using SCOND IF = T
    COPY Z401
    ENDIF
    IF        Z500  Checking the company code 5000 by using SCOND IF = T
    COPY Z501
    ENDIF
    In Z100 To  Z500 you should write a rule like ,
    Go to PE02 ,
    Query on company code ,
    if company code is 1000 than process else exit the process, for this you use SCOND IF= T else F.
    THanks
    Siva

  • SQL 2008, Update using multiple SubQuery

    Hello Experts , 
    I WANT TO DO THIS UPDATE WITHOUT USING CTE
    I have Two Table  REGION and AREA 
    REGION TABLE HAVE VALUE LIKE 
    Create Table REGIONtbl (REGION varchar(20),SomeArea varchar(20))
    Insert into REGIONtbl
    select 'REGION1','' union all
    select 'REGION2','' union all
    select 'REGION3','' 
    select *  from REGION
    OTHER table is AREA
    Create Table AREAtbl(AREAS  varchar(20))
    Insert into Areatbl
    select 'area1','' union all
    select 'area2','' union all
    select 'area3','' 
    I want to upadte AREAs in SomeArea column of Region Table ,
    I Need to first create autoincrement column in both Table using Row_Number function  and Upadte "SOMEAREA" column with "Areas" column 
    where ever ROW_Number ID of both the Table match 
    I tried below but did not work..
    UPDATE MASTER 
    SET MASTER.somearea =ar.areas
    FROM 
    SELECT Row_number() over (order by REGION) RN,
    REGION, somearea FROM REGIONtbl
    ) AS MASTER
    SELECT areas, ROW_NUMBER() OVER (ORDER BY areas)RNa
    FROM areatbl
    )AR
    where MASTER.rn=ar.rna
    HELP ?

    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. You have no idea.
    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. 
    >> I want to do this update without using CTE <<
    Why? Is that part of a homework assignment? 
    >> I have Two Tables REGION [sic] and AREA [sic] <<
    No, tables are sets so their names plural or collective nouns. Putting “tbl” in a name is called “tibble”, a common design flaw that we laugh at. Look for Phil Factor’s humor column on this. 
    Here is my guess at what you should have posted in order to do this the way you want to do it.
    CREATE SEQUENCE Region_Garbage
    AS INTEGER 
    START WITH 1 
    INCREMENT BY 1;
    CREATE SEQUENCE Area_Garbage
    AS INTEGER 
    START WITH 1 
    INCREMENT BY 1;
    CREATE TABLE Regions
    (region_name VARCHAR(20) NOT NULL PRIMARY KEY, 
     region_seq INTEGER NOT NULL,
     area_name VARCHAR(20) DEFAULT '' NOT NULL);
    INSERT INTO Regions (region_name, region_seq) 
    VALUES ('region_name1', NEXT VALUE FOR Region_Garbage);
    INSERT INTO Regions (region_name, region_seq) 
    VALUES ('region_name2', NEXT VALUE FOR Region_Garbage);
    INSERT INTO Regions (region_name, region_seq) 
    VALUES ('region_name3', NEXT VALUE FOR Region_Garbage);
    CREATE TABLE Areas
    (area_name VARCHAR(20) NOT NULL PRIMARY KEY,
     area_seq INTEGER NOT NULL);
    INSERT INTO Areas (area_name, area_seq) 
    VALUES ('area_name1', NEXT VALUE FOR area_Garbage);
    INSERT INTO Areas (area_name, area_seq) 
    VALUES ('area_name2', NEXT VALUE FOR area_Garbage);
    INSERT INTO Areas (area_name, area_seq) 
    VALUES ('area_name3', NEXT VALUE FOR area_Garbage);
    CREATE TABLE Areas
    (area_name VARCHAR(20) NOT NULL PRIMARY KEY,
     area_seq NEXT VALUE FOR Area_Garbage);
    >> I want to update area_name column of Regions Table <<
    I would fire you for doing this, but here is a stinking kludge.
    The term “Master” is from magnetic tape files, not RDBMS! Then to make it worse, you have used the old Sybase UPDATE. FROM.. syntax! It is unpredictable. Use the MERGE: 
    MERGE INTO Regions AS R
    USING Areas AS X
    ON X.area_seq = R.region_seq 
    WHEN MATCHED
    THEN UPDATE
         SET area_name = X.area_name;
    --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

  • Rearrange Submenus

    I'm working on a music DVD with 16 tracks or chapters. When I import the movie I get 3 submenus with tracks 1-6, 7-12 and 13-16. I would like to even it out and have 4 submenus with tracks 1-4, 5-8, 9-12 and 13-16. I can add a submenu but it's not th

  • Use iWeb '09 with Google Blog or Wordpress

    it's possible to use iWeb '09 with Google Blog or Wordpress? If it's possible, how? I'm still new to iWeb and blogging... Hope someone can help me with this...

  • Setup Sharepoint 2013 Extranet as separate farm

    Hi All We currently have a Sharepoint 2013 Intranet and would now like to setup a Sharepoint 2013 Extranet/Portal to allow external customers/clients a shared collaboration area to work with internal users.  The proposed site would be fairly basic an

  • Configuring Discussion and Announcement Connections to point to cluster

    Hello, I'm wondering how I'm supposed to configure my connection to the Discussion server for my Portal sites. I don't know if I'm suppose to point to the first node of the discussion server on the portal server 1 and to the second node of the discus

  • Life of iPod photo and where to sell?

    I want to sell my iPod photo while it's still alive. I have had it since December 2005, making it 1 year and 2 months old. I would like to know how long, typically, iPod photos last, and also where would be a good place to sell one? Gateway;   Window