[Forum FAQ] How do I create calculated measure using AMO in SQL Server Analysis Services?

Introduction
In SQL Server Analysis Services (SSAS), you can create a calculated measure in SQL Server Data Tool (SSDT)/Boniness Integrated Development Studio (BIDS). Sometimes you may need to create calculated measure by using AMO in a C# or VB project.
In this article, I will demonstrate so how to create calculated measure using AMO in SSAS?
Prerequisites
Before create calculated measure using AMO, you need to ensure that the following components were installed in your server.
The multidimensional database AdventureWorks Multidimensional Model 2012
A SQL Server with SSIS and SSAS installed
The AMO libraries installed:
X86 Package (SQL_AS_AMO.msi)
X64 Package (SQL_AS_AMO.msi)
Solution
Here is the detail steps to create calculated measure using AMO in SSAS.
Open SSDT and create a new SSIS project.
Drag Script Task to the design surface.
Click SSIS-> Variables to open the Variables window and add two variables that used to connect to the server and database.
Create a connection to connect to SSAS server.
Rename the connection name to ssas.
Double click the Script Task to open Script Task Editor.
Add Connection and Database variables to ReadWriteVariables textbox and then click Edit Script button.
Add AMO reference in the Solution Explore window.
Copy the script below and paste it into the script.
Dim objServer As Server
Dim objDatabase As Database
Dim strDataBaseID As String
Dim objCube As Cube
Dim objMdxScript As MdxScript
Dim objCommand As Command
Dim strCommand As String
objServer = New Server
objServer.Connect("localhost")
objDatabase = objServer.Databases("AdventureWorksDW2012Multidimensional-EE2")
strDataBaseID = objDatabase.ID
If objDatabase.Cubes.Count > 0 Then
objCube = objDatabase.Cubes("Adventure Works")
If objCube.MdxScripts.Count > 0 Then
objMdxScript = objCube.MdxScripts("MdxScript")
objMdxScript = objCube.MdxScripts(0)
Else
objCube.MdxScripts.Add("MdxScript", "MdxScript")
objMdxScript = objCube.MdxScripts("MdxScript")
End If
objCommand = New Command
strCommand = "CREATE MEMBER CURRENTCUBE.[Measures].[Multipy Measures By 3]"
strCommand = strCommand & " AS [Measures].[Internet Sales Amount] * 3, "
strCommand = strCommand & " VISIBLE = 1 ; "
objCommand.Text = strCommand
objMdxScript.Commands.Add(objCommand)
objMdxScript.Update()
objCube.Update()
End If
objServer.Disconnect()
Then you can run this SSIS package to create the calculated measure.
Applies to
Microsoft SQL Server 2005
Microsoft SQL Server 2008
Microsoft SQL Server 2008 R2
Microsoft SQL Server 2012
Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

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

Similar Messages

  • Creating OLAP report with Crystal Reports and SQL Server Analysis Services 2005

    Post Author: orahc_mao
    CA Forum: Data Connectivity and SQL
    Hi!
    I am currently using the trial version of the Crystal Reports XI and I wanted to do an OLAP report. The problem is I cannot select a cube using "OLAP Connection Browser" (the popup window). I already selected Microsoft OLE DB Provider and entered the server name but still can't connect.
    I don't think the problem is with SQL Server Analysis Services (2005) since Microsoft Excel - Import Data can detect the server as well as the cube I have created.
    I also tried the "Database Expert" of Crystal Reports, created an OLE DB (ADO) connection with "OLE DB Provider for OLAP Services 8.0" driver, entered the server name, checked the integrated security and then I can readily select the database created at SQL Server Analysis Services. However, I still need the OLAP grid create the report but it goes back to my original problem... selecting a cube.
    I hope somebody would help me with this issue.
    Thanks a lot!
    orahc_mao

    Hello,
    I don't recognize those variables as CR ones so it's likely something the original developer is setting in code.
    You'll have to discuss with that person.
    If your have SDK issues then post your question to one of the .NET or Java SDK forums.
    Thank you
    Don

  • How to align the text in justify format with SQL Server Reporting Services?

            How to align the text in justify format In SQL server Reporting Services? Is there any code to do so?

    Hi,
    I'm afraid that if you want to have this kind of functionality, you will need to write a custom control. Here is an example: http://msdn2.microsoft.com/en-us/library/ms345265.aspx. The issue with custom controls is that it needs to be known by all the reportservers that will render your report.
    Greetz,
    Geert
    Geert Verhoeven
    Consultant @ Ausy Belgium
    My Personal Blog

  • Create Fiat File Using Trigger in SQL Server

    Dear All,
        How to Create a Flat File using Trigger in SQL Server?

    Take a look at osql/sqlcmd, bcp, COM calls, xp_cmdshell, etc.  Here are a few links with code examples:
    https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/
    http://www.nigelrivett.net/SQLTsql/WriteTextFile.html
    http://stackoverflow.com/questions/8132663/creating-a-text-file-on-local-machine-using-sql-server-2008
    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

  • Please help: how to connect to SQL Server Analysis Service (OLAP cube) with Crystal Re[ort XI

    I'm trying to connect to an OLAP cube on our SQL Server 2005 machine which is running Analysis Services (9.0).  When I am trying to use the Crystal Reports menu follow steps mentioned below:
    1) New report -> Standard Report Wizard
    2) Create New Connection -> OLAP -> Add
         Source Type: MS OLE DB Provider fir Analysis Service 9.0
    But when I click buttone 'Test', CR prompt me: The connection could not be establiched. Faild to set properties.
    HOWEVER: I can connect SQl Server Analysis Server with Excel and other Report tools.
    Our softwares are as mentioned following:
    - OS: Windows 2003 Server
    - SQL Server: SQL Server 2005 Enterprise
    - Crystal Reports XI Release 2 Developer Edition
    And SQL Server & Crystal Report are running in the same PC.
    Any help?

    Please re-post if this is still an issue with your OLAP Connectivity please post to Business Objects  » Other Business Objects Products Forum or purchase a case and have a dedicated support engineer work with you directly

  • Creating alias for Web access to SQL Server Reporting Services

    Hello colleagues.
    I have MS SQL Server 2012 with SQL Server Reporting Services in domain "domain.local". In the local network at the entrance via Web browser to "mdr.domain.local/Reports" get into Reports of SQL Server Reporting Services and it's work fine.
    Necessary that the SQL Server Reporting Services could include via Web browser from alias "reports2.domain.local/Reports". To do this:
    1) I created a new A record "reports2" in the DNS leading to IP mdr.domain.local
    2) in Reporting Services Configuration Manager on a tab "Web Service URL" in "Report Server Web Service URLs" I add new record "http://reports2:80/ReportServer" (host Header Name: reports2)
    BUT "reports2.domain.local/Reports" is not work. When entering to "reports2.domain.local/Reports" I see page "An error in the security certificate for this Web Site..." and when I click "Continue to ...", then "Unable
    to find a web page."
    What and where I must add/change for work of alias "reports2.domain.local/Reports" by analogy with "mdr.domain.local/Reports"?
    I hope for your help.
    Thanks.

    WooW it's work!!! Thank you
    JJordheim  you are the best!
    With my PKI I create new certificate for "reports2.domain.local" and Import it to MDR server (in Personal). I create new network adapter and configure Reporting Services Configuration on "Report manager URL" tab (for SSL):
    mdr.domain.local - certificate "mdr.domain.local" - network adapter №1
    reports2.domain.local - certificate "reports2.sygroup.local" - network adapter №2
    And all work fine.
    If I configure all to 1 network adapter it's doesn't work.
    Thanks for help!

  • How to tell whether a license used to install SQL Server is MSDN license or Volume license?

    I want to check license used to install SQL Server is MSDN license or Volume license for SQL Servers which are at least SQL Server 2008 on Windows 2008 R2.  Is there any script/command/tool that I can run on Windows or SQL Server to find such
    information? 

    Hello,
    This is a community forum for technical questions & issues.
    For question regarding pricing / licensing please contact a Microsoft sales partner or licensing expert.
    Call (1-800-426-9400), Monday through Friday, 6:00 AM to 6:00 PM PST to speak directly to Microsoft licensing specialist.
    http://www.microsoft.com/en-us/server-cloud/products/sql-server/buy.aspx
    T-SQL Articles
    T-SQL e-book by TechNet Wiki Community
    T-SQL blog

  • [Forum FAQ] How do I send multiple rows returned by Execute SQL Task as Email content in SQL Server Integration Services?

    Question:
    There is a scenario that users want to send multiple rows returned by Execute SQL Task as Email content to send to someone. With Execute SQL Task, the Full result set is used when the query returns multiple rows, it must map to a variable of the Object data
    type, then the return result is a rowset object, so we cannot directly send the result variable as Email content. Is there a way that we can extract the table row values that are stored in the Object variable as Email content to send to someone?
    Answer:
    To achieve this requirement, we can use a Foreach Loop container to extract the table row values that are stored in the Object variable into package variables, then use a Script Task to write the data stored in packages variables to a variable, and then set
    the variable as MessageSource in the Send Mail Task. 
    Add four variables in the package as below:
    Double-click the Execute SQL Task to open the Execute SQL Task Editor, then change the ResultSet property to “Full result set”. Assuming that the SQL Statement like below:
    SELECT   Category, CntRecords
    FROM         [table_name]
    In the Result Set pane, add a result like below (please note that we must use 0 as the result set name when the result set type is Full result set):
    Drag a Foreach Loop Container connects to the Execute SQL Task. 
    Double-click the Foreach Loop Container to open the Foreach Loop Editor, in the Collection tab, change the Enumerator to Foreach ADO Enumerator, then select User:result as ADO object source variable.
    Click the Variable Mappings pane, add two Variables as below:
    Drag a Script Task within the Foreach Loop Container.
    The C# code that can be used only in SSIS 2008 and above in Script Task as below:
    public void Main()
       // TODO: Add your code here
                Variables varCollection = null;
                string message = string.Empty;
                Dts.VariableDispenser.LockForWrite("User::Message");
                Dts.VariableDispenser.LockForWrite("User::Category");
                Dts.VariableDispenser.LockForWrite("User::CntRecords");     
                Dts.VariableDispenser.GetVariables(ref varCollection);
                //Format the query result with tab delimiters
                message = string.Format("{0}\t{1}\n",
                                            varCollection["User::Category"].Value,
                                            varCollection["User::CntRecords"].Value
               varCollection["User::Message"].Value = varCollection["User::Message"].Value + message;   
               Dts.TaskResult = (int)ScriptResults.Success;
    The VB code that can be used only in SSIS 2005 and above in Script Task as below, please note that in SSIS 2005, we should
    change PrecompileScriptIntoBinaryCode property to False and Run64BitRuntime property to False
    Public Sub Main()
            ' Add your code here
            Dim varCollection As Variables = Nothing
            Dim message As String = String.Empty
            Dts.VariableDispenser.LockForWrite("User::Message")
            Dts.VariableDispenser.LockForWrite("User::Category")
            Dts.VariableDispenser.LockForWrite("User::CntRecords")
            Dts.VariableDispenser.GetVariables(varCollection)
            'Format the query result with tab delimiters
            message = String.Format("{0}" & vbTab & "{1}" & vbLf, varCollection("User::Category").Value, varCollection("User::CntRecords").Value)
            varCollection("User::Message").Value = DirectCast(varCollection("User::Message").Value,String) + message
            Dts.TaskResult = ScriptResults.Success
    End Sub
    Drag Send Mail Task to Control Flow pane and connect it to Foreach Loop Container.
    Double-click the Send Mail Task to specify the appropriate settings, then in the Expressions tab, use the Message variable as the MessageSource Property as below:
    The final design surface like below:
    References:
    Result Sets in the Execute SQL Task
    Applies to:
    Integration Services 2005
    Integration Services 2008
    Integration Services 2008 R2
    Integration Services 2012
    Integration Services 2014
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

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

  • How to extract a tagged string using XML in sql server 2014?

    A column stores the string data with tag as below.I have to retrieve the value of ATRB_C1 as val1234 through xml
    Query:
    CREATE TABLE #test (col varchar(500))
    INSERT INTO #test VALUES('< ATRB_C value ="val1" />< ATRB_C1 value ="val234" />')
    SELECT * FROM  #test FOR XML RAW
    Output:
    <row col="&lt; ATRB_C value =&quot;val1&quot; /&gt;&lt; ATRB_C1 value =&quot;val234&quot; /&gt;" />
    Since the format is incorrect, not able to extract using xml.value
    Any help would be appreciated!!

    CREATE TABLE #test (col xml)
    INSERT INTO #test(col) VALUES('<ATRB_C value ="val1"/><ATRB_C1 value ="val234" />')
    SELECT * FROM #test
    Select Col1.value('(@value)[1]','varchar(20)') as [tab1_col1],col2.value('(@value)[1]','varchar(20)') as [tab2_col2]
    from #test cross apply col.nodes('/ATRB_C') as tab1(col1)
    cross apply col.nodes('/ATRB_C1') as tab2(col2)
    drop table #test
    Hope it Helps!!

  • Create OLE DB Data Source in Sql Server Reporting Services

    Hi,
    I need to connect to a sap bw cube and when i try to create Data Source everything is going well but i can't see my cubes in the catalog field.
    any one have experience with it??
    Thanks.

    Hi Gil,
    Check whether the cube is present in the below table.
    RSDCUBE: Directory of InfoCubes / InfoProvider.
    Regards,
    KK.

  • How save & retrive data from database using flex, coldfusion, sql server

    hi , i am very new in flex, i am trying to insert data in
    database using flex2, coldfusion, sql server. any one can help me
    please. or give me any example.

    Hi try to goto the following sites, you will get some
    direction to think
    http://weblogs.macromedia.com/pent/archives/2006/11/example_of_flex.cfm
    http://pdxphp.org/node/258
    Good Luck

  • How to show or publish the TFS - SQL Server Reporting Services reports in SharePoint dashboard?

    Hello,
    We have configured SharePoint site and SSRS for a team project.
    Foll. is the SharePoint site for the team project. When we click on the REPORTS link, it redirects us to the SQL Server Reporting Services website.
    My question is: How can I show or publish the reports from  SQL Server Reporting Services into SharePoint so that I can view the reports on SharePoint dashboard rather than having to go to the SSRS URL?

    Hi Nachiket,
    If you configure Reporting service for your TFS, then you can view the reports in report manger site when you click click report on Team Explorer. And SharePoint is a collaboration website product that offers deep integration with Office products like Word,
    Outlook, and Excel. You can save your team project related files in your SharePoint site. Check this
    page for more details.
    If you want to view reports that generated by reporting service on your SharePoint site, you might need to save the report in Excel and upload it to SharePoint site.
    Best regards, 

  • How to install Studio, DataTools, SSIS and SSAS to SQL Server 2014 RTM DataWarehousing

    I have fresh installation of VM. Plan is to build DW and SSAS OLAP Cube.
    How to install needed services and tools as they are not installed as default?
    If I click SQL Server Installation Center and choose Installation and New SQL Server, I'm guided to choose file, but don't know where to find.
    Kenny_I

    Hi Kenny_I,
    According to your description, you want to add SQL Srever Data Tools, SQL Server Integration Services and SQL Server Analysis Services to your existing installation, so you click SQL Server Installation Center and choose Installation and New SQL Server,
    nad now you are guided to choose file, right?
    In this case, you need to choose the folder which contains SQL Server installation media. I have tested it on my local environment, after select correct folder and click "Ok" button, everything works fine.
    Reference.
    http://msdn.microsoft.com/en-us/library/ms143219.aspx
    If you have any questions, please feel free to ask.
    Regards,
    Charlie Liao
    If you have any feedback on our support, please click
    here
    Charlie Liao
    TechNet Community Support

  • [Forum FAQ] How to configure a Data Driven Subscription which get multi-value parameters from one column of a database table?

    Introduction
    In SQL Server Reporting Services, we can define a mapping between the fields that are returned in the query to specific delivery options and to report parameters in a data-driven subscription.
    For a report with a parameter (such as YEAR) that allow multiple values, when creating a data-driven subscription, how can we pass a record like below to show correct data (data for year 2012, 2013 and 2014).
    EmailAddress                             Parameter                      
    Comment
    [email protected]              2012,2013,2014               NULL
    In this article, I will demonstrate how to configure a Data Driven Subscription which get multi-value parameters from one column of a database table
    Workaround
    Generally, if we pass the “Parameter” column to report directly in the step 5 when creating data-driven subscription.
    The value “2012,2013,2014” will be regarded as a single value, Reporting Services will use “2012,2013,2014” to filter data. However, there are no any records that YEAR filed equal to “2012,2013,2014”, and we will get an error when the subscription executed
    on the log. (C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\LogFiles)
    Microsoft.ReportingServices.Diagnostics.Utilities.InvalidReportParameterException: Default value or value provided for the report parameter 'Name' is not a valid value.
    This means that there is no such a value on parameter’s available value list, this is an invalid parameter value. If we change the parameter records like below.
    EmailAddress                        Parameter             Comment
    [email protected]         2012                     NULL
    [email protected]         2013                     NULL
    [email protected]         2014                     NULL
    In this case, Reporting Services will generate 3 reports for one data-driven subscription. Each report for only one year which cannot fit the requirement obviously.
    Currently, there is no a solution to solve this issue. The workaround for it is that create two report, one is used for view report for end users, another one is used for create data-driven subscription.
    On the report that used create data-driven subscription, uncheck “Allow multiple values” option for the parameter, do not specify and available values and default values for this parameter. Then change the Filter
    From
    Expression:[ParameterName]
    Operator   :In
    Value         :[@ParameterName]
    To
    Expression:[ParameterName]
    Operator   :In
    Value         :Split(Parameters!ParameterName.Value,",")
    In this case, we can specify a value like "2012,2013,2014" from database to the data-driven subscription.
    Applies to
    Microsoft SQL Server 2005
    Microsoft SQL Server 2008
    Microsoft SQL Server 2008 R2
    Microsoft SQL Server 2012
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    For every Auftrag, there are multiple Position entries.
    Rest of the blocks don't seems to have any relation.
    So you can check this code to see how internal table lt_str is built whose first 3 fields have data contained in Auftrag, and next 3 fields have Position data. The structure is flat, assuming that every Position record is related to preceding Auftrag.
    Try out this snippet.
    DATA lt_data TYPE TABLE OF string.
    DATA lv_data TYPE string.
    CALL METHOD cl_gui_frontend_services=>gui_upload
      EXPORTING
        filename = 'C:\temp\test.txt'
      CHANGING
        data_tab = lt_data
      EXCEPTIONS
        OTHERS   = 19.
    CHECK sy-subrc EQ 0.
    TYPES:
    BEGIN OF ty_str,
      a1 TYPE string,
      a2 TYPE string,
      a3 TYPE string,
      p1 TYPE string,
      p2 TYPE string,
      p3 TYPE string,
    END OF ty_str.
    DATA: lt_str TYPE TABLE OF ty_str,
          ls_str TYPE ty_str,
          lv_block TYPE string,
          lv_flag TYPE boolean.
    LOOP AT lt_data INTO lv_data.
      CASE lv_data.
        WHEN '[Version]' OR '[StdSatz]' OR '[Arbeitstag]' OR '[Pecunia]'
             OR '[Mita]' OR '[Kunde]' OR '[Auftrag]' OR '[Position]'.
          lv_block = lv_data.
          lv_flag = abap_false.
        WHEN OTHERS.
          lv_flag = abap_true.
      ENDCASE.
      CHECK lv_flag EQ abap_true.
      CASE lv_block.
        WHEN '[Auftrag]'.
          SPLIT lv_data AT ';' INTO ls_str-a1 ls_str-a2 ls_str-a3.
        WHEN '[Position]'.
          SPLIT lv_data AT ';' INTO ls_str-p1 ls_str-p2 ls_str-p3.
          APPEND ls_str TO lt_str.
      ENDCASE.
    ENDLOOP.

  • [Forum FAQ] How do I restore the CDC enabled database backups (FULL + DIFF) while maintaining the CDC integrity

    Question
    Background: When restoring Full + DIFF backups of a Change Data Capture (CDC) enabled database to a different SQL server, the CDC integrity is not being maintained. We did RESTORE the databases with the KEEP_CDC option.
    How do I successfully restore the CDC enabled database backups (FULL + DIFF) while maintaining the CDC integrity?
    Answer
    When restoring a CDC enabled database on a different machine that is running SQL Server, besides using use the KEEP_CDC option to retain all the CDC metadata, you also need to add Capture and Cleanup jobs. 
    In addition, as you want to restore FULL + DIFF backups of a CDC enabled database, you need to note that the KEEP_CDC and NoRecovery options are incompatible. Use the KEEP_CDC option only when you are completing the recovery. I made a test to display
    the whole process that how to restore the CDC enabled database backups (FULL + DIFF) on a different machine.
    Create a database named ’CDCTest’ in SQL Server 2012, then enable the CDC feature and take full+ differential backups of the database.
    -- Create database CDCTest
    CREATE DATABASE [CDCTest] ON  PRIMARY
    ( NAME = N'CDCTest ', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\ CDCTest.mdf' , SIZE = 5120KB ,
    MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
     LOG ON
    ( NAME = N'CDCTest _log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\ CDCTest _log.LDF' , SIZE = 3840KB ,
    MAXSIZE = 2048GB , FILEGROWTH = 10%)
    GO
    use CDCTest;
    go
    -- creating table
    create table Customer
    custID int constraint PK_Employee primary key Identity(1,1)
    ,custName varchar(20)
    --Enabling CDC on CDCTest database
    USE CDCTest
    GO
    EXEC sys.sp_cdc_enable_db
    --Enabling CDC on Customer table
    USE CDCTest
    GO
    EXEC sys.sp_cdc_enable_table
    @source_schema = N'dbo',
    @source_name = N'Customer',
    @role_name = NULL
    GO
    --Inserting values in customer table
    insert into Customer values('Mike'),('Linda')
    -- Querying CDC table to get the changes
    select * from cdc.dbo_customer_CT
    --Taking full database backup
    backup database CDCTest to disk = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\ CDCTest.bak'
    insert into Customer values('David'),('Jane')
    -- Querying CDC table to get the changes
    select * from cdc.dbo_customer_CT
    --Taking differential database backup
    BACKUP DATABASE CDCTest TO DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\ CDCTestdif.bak' WITH DIFFERENTIAL
    GO
    Restore Full backup of the ‘CDCTest’ database with using KEEP_CDC option in a different server that is running SQL Server 2014.
    Use master
    Go
    --restore full database backup
    restore database CDCTest from disk = 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\Backup\CDCTest.bak' with keep_cdc
    Restore Diff backup of the ‘CDCTest’ database.
    Restore Database CDCTest From Disk = 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\Backup\CDCTest.bak'
        With Move 'CDCTest' To 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA\CDCTest.mdf',
            Move 'CDCTest _log' To 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA\CDCTest _log.LDF',
            Replace,
            NoRecovery;
    Go
    --restore differential database backup
    restore database CDCTest from disk = 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\Backup\CDCTestdif.bak' with keep_cdc
    Add the Capture and Cleanup jobs in the CDCTest database.
    --add the Capture and Cleanup jobs
    Use CDCTest
    exec sys.sp_cdc_add_job 'capture'
    GO
    exec sys.sp_cdc_add_job 'cleanup'
    GO
    insert into Customer values('TEST'),('TEST1')
    -- Querying CDC table to get the changes
    select * from cdc.dbo_customer_CT
    Reference
    Track Data Changes (SQL Server)
    Restoring a SQL Server database that uses Change Data Capture
    Applies to
    SQL Server 2014
    SQL Server 2012
    SQL Server 2008 R2
    SQL Server 2008
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    Question
    Background: When restoring Full + DIFF backups of a Change Data Capture (CDC) enabled database to a different SQL server, the CDC integrity is not being maintained. We did RESTORE the databases with the KEEP_CDC option.
    How do I successfully restore the CDC enabled database backups (FULL + DIFF) while maintaining the CDC integrity?
    Answer
    When restoring a CDC enabled database on a different machine that is running SQL Server, besides using use the KEEP_CDC option to retain all the CDC metadata, you also need to add Capture and Cleanup jobs. 
    In addition, as you want to restore FULL + DIFF backups of a CDC enabled database, you need to note that the KEEP_CDC and NoRecovery options are incompatible. Use the KEEP_CDC option only when you are completing the recovery. I made a test to display
    the whole process that how to restore the CDC enabled database backups (FULL + DIFF) on a different machine.
    Create a database named ’CDCTest’ in SQL Server 2012, then enable the CDC feature and take full+ differential backups of the database.
    -- Create database CDCTest
    CREATE DATABASE [CDCTest] ON  PRIMARY
    ( NAME = N'CDCTest ', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\ CDCTest.mdf' , SIZE = 5120KB ,
    MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
     LOG ON
    ( NAME = N'CDCTest _log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\ CDCTest _log.LDF' , SIZE = 3840KB ,
    MAXSIZE = 2048GB , FILEGROWTH = 10%)
    GO
    use CDCTest;
    go
    -- creating table
    create table Customer
    custID int constraint PK_Employee primary key Identity(1,1)
    ,custName varchar(20)
    --Enabling CDC on CDCTest database
    USE CDCTest
    GO
    EXEC sys.sp_cdc_enable_db
    --Enabling CDC on Customer table
    USE CDCTest
    GO
    EXEC sys.sp_cdc_enable_table
    @source_schema = N'dbo',
    @source_name = N'Customer',
    @role_name = NULL
    GO
    --Inserting values in customer table
    insert into Customer values('Mike'),('Linda')
    -- Querying CDC table to get the changes
    select * from cdc.dbo_customer_CT
    --Taking full database backup
    backup database CDCTest to disk = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\ CDCTest.bak'
    insert into Customer values('David'),('Jane')
    -- Querying CDC table to get the changes
    select * from cdc.dbo_customer_CT
    --Taking differential database backup
    BACKUP DATABASE CDCTest TO DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\ CDCTestdif.bak' WITH DIFFERENTIAL
    GO
    Restore Full backup of the ‘CDCTest’ database with using KEEP_CDC option in a different server that is running SQL Server 2014.
    Use master
    Go
    --restore full database backup
    restore database CDCTest from disk = 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\Backup\CDCTest.bak' with keep_cdc
    Restore Diff backup of the ‘CDCTest’ database.
    Restore Database CDCTest From Disk = 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\Backup\CDCTest.bak'
        With Move 'CDCTest' To 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA\CDCTest.mdf',
            Move 'CDCTest _log' To 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA\CDCTest _log.LDF',
            Replace,
            NoRecovery;
    Go
    --restore differential database backup
    restore database CDCTest from disk = 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\Backup\CDCTestdif.bak' with keep_cdc
    Add the Capture and Cleanup jobs in the CDCTest database.
    --add the Capture and Cleanup jobs
    Use CDCTest
    exec sys.sp_cdc_add_job 'capture'
    GO
    exec sys.sp_cdc_add_job 'cleanup'
    GO
    insert into Customer values('TEST'),('TEST1')
    -- Querying CDC table to get the changes
    select * from cdc.dbo_customer_CT
    Reference
    Track Data Changes (SQL Server)
    Restoring a SQL Server database that uses Change Data Capture
    Applies to
    SQL Server 2014
    SQL Server 2012
    SQL Server 2008 R2
    SQL Server 2008
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

Maybe you are looking for

  • OdbcDataAdapter.Fill() not getting all rows from RDB using 64bit driver

    I am using VS2012 Pro on Windows 7 (64-bit). I am migrating an older 32-bit VS2008 app to the new environment. I'm building for the .NET Framework 4.5. The app queries an RDB database and uses the Oracle RDB drivers version 3.3.2.0. When I build as a

  • How do I get Apple to update timezone quickly?

    Hi all. How do I make contact with the appropriate team at Apple to have the timezone data updated as soon as possible? The local time law has been change (actually, twice this year). The old law indicated that DST was to be changed back to winter ti

  • What are Layers? And why do I need them?

    WHAT ARE LAYERS? AND WHY DO I NEED THEM? Layers are an essential part of Photoshop. With Layers you can separate pictures or design elements from each other, as if they are stacked on pieces of glass. With all elements separate, you can move or chang

  • Any way to work with multiple layers once map is mapped to a sphere?

    I'm working on a history documentary about World War II and I have a map of the world divided into colonial empires. Each empire is a separate layer. I know how to take the world map and apply it to a sphere in Photoshop CS4 Extended. The problem is

  • I have to keep fixing and re-fixing the same broken links in iTunes

    Does anyone have a reason, or better yet, a solution as to why I have to keep re-fixing the same dead tracks in iTunes 11? It doesn't seem to matter if i Use 3rd party apps or iTunes Locate feature, I can fix a link then it will just be broken again