Insert missing records dynamically in SQL Server 2008 R2

Hi, I am working on a requirement where I will have to work on some % calculations for 2 different states where we do business. The task that I am trying to accomplish is technically we need to have any Product sales in both the states if not for instance
in the following example ProductC does not have sales in OR so I need to insert a record for ProductC - OR with 0. This is an intermediary resultset of all the calculations that I am working with.
Example Dataset:
CREATE TABLE [dbo].[Product](
[Product] [varchar](18) NOT NULL,
[State] [varchar](5) NOT NULL,
[Area1] [int] NOT NULL,
[Area2] [int] NOT NULL,
[Area3] [int] NOT NULL,
[Area4] [int] NOT NULL,
[Area5] [int] NOT NULL,
[Area6] [int] NOT NULL,
[Area7] [int] NOT NULL,
[Area8] [int] NOT NULL,
[Area9] [int] NOT NULL,
[Area10] [int] NOT NULL,
[Total] [int] NULL
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductA','OR',0,0,2,0,2,0,0,0,0,0,4)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductA','WA',0,0,1,0,0,0,0,0,0,0,1)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductA','Total',0,0,3,0,2,0,0,0,0,0,5)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductB','OR',0,0,5,0,0,0,0,0,0,0,5)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductB','WA',0,0,2,0,0,1,0,0,0,0,3)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductB','Total',0,0,7,0,0,1,0,0,0,0,8)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductC','WA',0,0,0,0,0,0,0,0,0,1,1)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductC','Total',0,0,0,0,0,0,0,0,0,1,1)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductD','OR',5,2,451,154,43,1,0,0,0,0,656)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductD','WA',0,20,102,182,58,36,0,1,0,0,399)
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductD','Total',5,22,553,336,101,37,0,1,0,0,1055)
How to accomplish this in SQL Server 2008 R2.
Insert missing record:
INSERT INTO [Product] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductC','OR',0,0,0,0,0,0,0,0,0,0,0)
Thanks in advance......
Ione

CREATE TABLE [dbo].[Products](
[Product] [varchar](18) NOT NULL,
[State] [varchar](5) NOT NULL,
[Area1] [int] NOT NULL,
[Area2] [int] NOT NULL,
[Area3] [int] NOT NULL,
[Area4] [int] NOT NULL,
[Area5] [int] NOT NULL,
[Area6] [int] NOT NULL,
[Area7] [int] NOT NULL,
[Area8] [int] NOT NULL,
[Area9] [int] NOT NULL,
[Area10] [int] NOT NULL,
[Total] [int] NULL
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductA','OR',0,0,2,0,2,0,0,0,0,0,4)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductA','WA',0,0,1,0,0,0,0,0,0,0,1)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductA','Total',0,0,3,0,2,0,0,0,0,0,5)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductB','OR',0,0,5,0,0,0,0,0,0,0,5)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductB','WA',0,0,2,0,0,1,0,0,0,0,3)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductB','Total',0,0,7,0,0,1,0,0,0,0,8)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductC','WA',0,0,0,0,0,0,0,0,0,1,1)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductC','Total',0,0,0,0,0,0,0,0,0,1,1)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductD','OR',5,2,451,154,43,1,0,0,0,0,656)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductD','WA',0,20,102,182,58,36,0,1,0,0,399)
INSERT INTO [Products] ([Product],[State],[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])VALUES('ProductD','Total',5,22,553,336,101,37,0,1,0,0,1055)
;WIth mycte as (
Select Product,State From (Select distinct Product from Products) p, (
Select distinct State from Products) s
Insert into [Products](Product,State,[Area1],[Area2],[Area3],[Area4],[Area5],[Area6],[Area7],[Area8],[Area9],[Area10],[Total])
Select m.Product,m.State
,0,0,0,0,0,0,0,0,0,0,0
from mycte m Left Join Products p on m.[Product]=p.Product and m.State=p.State
WHERE p.Product is null and p.State is null
select * from Products
Order by Product
,Case when State='Total' Then 2 else 1 End
Drop table Products

Similar Messages

  • Inserting data from Oracle to SQL Server 2008

    Hi All,
    I am using oracle 9.2.0.7 and SQL server 2008 in windows server 2003 operating system.
    My requirment is like below.
    1) I would liek to insert data from the Oracle database to SQL Server.
    For the above requirement we have created the ODBC, then configure the listener file, tns file, and created the db link. This part is working fine as I am able to select the data from the SQL Server.
    But when I am inserting the record from the oracle database to the SQL Server I am getting the error, (ORA-00904) Here oracle can not identified the column name.
    My insert statement is like below.
    insert into test@SQLTEST (name, fullname)
    values ('Oracle', 'Oracle server data');
    Test is the SQL server table name and sqltest is the db link name.
    If I am select the data
    select * from test@SQLTEST from Oralce I am getting the data properly.
    Thanks,
    SUN
    Edited by: User SUN@ on Jun 9, 2010 5:49 PM

    Hi,
    I modify the column name as "f_name" and "l_name";
    Still I am getting the same error;
    Thanks,
    SUN

  • Transfer tables from sql server 2008 to oracle 11g

    Hi ,
    I have to transfer 2-3 tables (5 Lacs records each) from sql server 2008 to oracle Ent. 11g (platform Linux)
    i have to upload data with some conditions.
    not allowed to install oracle client on sql server for link server. i can get data in csv file
    which will be the best possible way
    1) using Db link on oracle server
    2) get data into csv file and load using SQL loader
    3) get data into csv and load using external table
    4) using tool - sql developer
    Thanx,

    user10188639 wrote:
    Hi ,
    I have to transfer 2-3 tables (5 Lacs records each) from sql server 2008 to oracle Ent. 11g (platform Linux)
    i have to upload data with some conditions.
    not allowed to install oracle client on sql server for link server. i can get data in csv file
    which will be the best possible way
    1) using Db link on oracle server
    2) get data into csv file and load using SQL loader
    3) get data into csv and load using external table
    4) using tool - sql developer
    Thanx,
    >which will be the best possible way
    which metric measures best? is higher or lower value better?
    How will you, I or anyone recognize which option is best solution?

  • Insert data from SQL Server 2008 St.Ed to ORACLE 11gr2 St. Edition

    Dear all,
    I'm searching a solution for faster transmission of data of a db SQL Server (2008 St. edition) vs PROD db that is an ORACLE 11gr2 St. edition too.
    Actually this operation spend 1,5 hours but I'd like cut this time because size of the data grow up in future and this time could be a serious problem ....
    Looking on Oracle Enterprise Manager I've seen that main problem is about commit .. SQL Server every record insert into Oracle TBL generate a commit  ... unfortunately I cannot insert when commit must be done ... If will be solved it probably may be solved situation ...
    Thanks in advance for every idea.
    Andrea

    Nardo wrote:
    SQL server is connect with Oracle DB by OLEDB, commit every record is why SQL haven't possibility of manage it ... anyway I'm sorry for delay of the answer, I've solved using sqlloader ... faster and without impact ... must be have hight attention if there will be change any field ... that's all.
    REDO upgrade was done like first step because anyway it was too small.
    Thanks for you answer and sorry again for delay !!!!
    Thanks.
    If you are depending on MS SQL server technology to do this, you are going to be stuck with the performance of that technology.
    A few weeks ago we had a need to load institute a daily load of or DW from a MSSQL database.  The MS-centric person responsible developed a procedure (using MS tools) that took 4.5 hours to load 1.2 million rows.  I ran a session trace and the tkprof report revealed exactly what has already been described.  Single row insert and commit.  I knocked together a PL/SQL procedure that did a single INSERT .. (SELECT .. FROM TABLE@MSSQL). and it ran in 4 minutes.  Using the Oracle transparent gateway for ODBC.

  • Tables missing in SQL Server 2008 for Hyperion Application

    Hello Experts,
    I am cuurently working on Hyperion Finacial close management (Account Reconciliation Manager) application version 11.1.2.3, O.S is Windows 2008 R2 and relational database is SQL Server 2008.
    When I am trying to copy Account Profiles to a period say go to Manage->Periods->Right Click->Copy to Periods, I get the error:
    Object arm_access is missing.
    When I open SQL server studio, I can clearly see table 'ARM_ACCESS' but when I did a search on oracle support and google, I found out that it is a case sensitive issue and the table has to be in small letters.
    So I created a new table 'arm_access' with all columns as there are in 'ARM_ACCESS' in SQL Server 2008, but it is not fetching any data.
    Can anyone provide me the query that I can run to display the same structure and data for 'arm_access'?
    If anyone is using the instance, he/she should be able to provide me the query that I can run in SQL server 2008 to populate the 'arm_access' table.
    Appreciate your help as this is stopping my development work.
    Thanks in advance.
    Regards,
    Sumit

    Hi Sumit,
    Its just a wild guess am not sure with this.
    i dont have idea about query in sql server. but it oracle it would be something like create table targettablename as select * from sourcetablename.
    Ideally it will not allow to create you a table with that name if its already exists i mean its case insensitive (. Even if you have created manually make sure the db user you created with has select privilage granted for all users or the user you configured in Financial close management) or the DB might not be having select privilage .
    Note:Have backups in place when you are manually to manipulate or changing the database user.
    Thanks
    Amith

  • SQL Server 2008 - RS - Loop of multiple Bulk Inserts

    Hi,
    I want to import multiple flat files to a table on SQL Server 2008 R2. However, I don't have access to Integration Services to use a foreach loop, so I'm doing the process using T-SQL. Actually, I'm using manually code to which file to introduce the data on
    tables. My code are like this:
    cREATE TABLE #temporaryTable
        [column1] [varchar](100) NOT NULL,
        [column2 [varchar](100) NOT NULL
    BULK
    INSERT #temp
    FROM 'C:\Teste\testeFile01.txt' 
    WITH
    FIELDTERMINATOR = ';',
    ROWTERMINATOR = '\n',
    FIRSTROW = 1
    GO
    BULK
    INSERT #temp
    FROM 'C:\Teste\testeFile02.txt' 
    WITH
    FIELDTERMINATOR = ';',
    ROWTERMINATOR = '\n',
    FIRSTROW = 1
    GO
    -------------------------------------------------INSERT INTO dbo.TESTE ( Col_1, Col_2)
    Select RTRIM(LTRIM([column1])), RTRIM(LTRIM([column2])) From #temporaryTable
    IF EXISTS(SELECT * FROM #temporaryTable) drop table #temporaryTable
    The problem is that I have 20 flat files to Insert... Do I have any loop solution in T-SQL to insert all the flat files on same table?
    Thanks!

    Here is a working sample of powershell script I adopted from internet( I don't have the source handy now).
    Import-Module -Name 'SQLPS' -DisableNameChecking
    $workdir="C:\temp\test\"
    $svrname = "MC\MySQL2014"
    Try
    #Change default timeout time from 600 to unlimited
    $svr = new-object ('Microsoft.SqlServer.Management.Smo.Server') $svrname
    $svr.ConnectionContext.StatementTimeout = 0
    $table="test1.dbo.myRegions"
    #remove the filename column in the target table
    $q1 = @"
    Use test1;
    IF COL_LENGTH('dbo.myRegions','filename') IS NOT NULL
    BEGIN
    ALTER TABLE test1.dbo.myRegions DROP COLUMN filename;
    END
    Invoke-Sqlcmd -ServerInstance $svr.Name -Database master -Query $q1
    $dt = (get-date).ToString("yyyMMdd")
    $formatfilename="$($table)_$($dt).xml"
    $destination_formatfilename ="$($workdir)$($formatfilename)"
    $cmdformatfile="bcp $table format nul -c -x -f $($destination_formatfilename) -T -t\t -S $($svrname) "
    Invoke-Expression $cmdformatfile
    #Delay 1 second
    Start-Sleep -s 1
    $q2 = @"
    Alter table test1.dbo.myRegions Add filename varchar(500) Null;
    #add the filename column to the target table
    Invoke-Sqlcmd -ServerInstance $svr.Name -Database master -Query $q2
    $files = Get-ChildItem $workdir
    $items = $files | Where-Object {$_.Extension -eq ".txt"}
    for ($i=0; $i -lt $items.Count; $i++) {
    $strFileName = $items[$i].Name
    $strFileNameNoExtension= $items[$i].BaseName
    $query = @"
    BULK INSERT test1.dbo.myRegions from '$($workdir)$($strFileName)' WITH (FIELDTERMINATOR = '\t', FIRSTROW = 2, FORMATFILE = '$($destination_formatfilename)');
    Invoke-Sqlcmd -ServerInstance $svr.Name -Database master -Query $query -querytimeout 65534
    #Delay 10 second
    Start-Sleep -s 10
    # Update the filename column
    Invoke-Sqlcmd -ServerInstance $svr.Name -Database master -querytimeout 65534 -Query "Update test1.dbo.myRegions SET filename= '$($strFileName)' WHERE filename is null; "
    # Move uploaded file to archive
    If ((Test-Path "$($workdir)$($strFileName)") -eq $True) { Move-Item -Path "$($workdir)$($strFileName)" -Destination "$($workdir)Processed\$($strFileNameNoExtension)_$($dt).txt"}
    Catch [Exception]
    write-host "--$strFileName "$_.Exception.Message

  • Missing MSI files SQL Server 2008 R2 SP3

    I have hit an issue while installing Service Pack 3 for SQL Server 2008 R2. The existing version is
    10.50.4295.0 (SP2+CU9)
     When running the SP3 file the following error occurs
    SQL Server Setup has encountered the following error:
    The cached MSI file 'C:\Windows\Installer\91a4f43.msi' is missing.
    Its original file is 'sql_engine_core_inst.msi' and it was installed for product 'SQL Server 2008 R2 SP2 Database Engine Services' from '\\ServerName\Share$\SQL\SQL105\ENT\x64\setup\sql_engine_core_inst_msi\', version '10.52.4000.0', language 'ENU'.
    To resolve this problem, recover the missing file from the installation media and start setup again.
    For more information about how to resolve this problem, see 'Steps to restore the missing Windows Installer cache files' (http://go.microsoft.com/fwlink/?LinkId=144387) in the Microsoft Knowledge Base.
    Error code 0x84B20002.
    The next I tried to remove CU9 before applying SP3. The following error occurred when CU 9 was attempted to be removed.
    The cached patch file 'C:Windows\Installer\483c7040.msp' is missing.

    Hello Alberto,
    I tried this link
    http://support.microsoft.com/kb/969052
    Using the VB script FindSQLInstall I tried getting some details about the missing MSI files. Just sharing the details incase you may have some details or better insight on what it says.
    !!!! C:\Windows\Installer\91a4f43.msi DOES NOT exist in the Installer cache. !!!!
          Action needed, recreate or re-establish path to the directory:
    \\Servername\Sharename$\SQL\SQL105\ENT\x64\setup\sql_engine_core_inst_msi\then rerun this script to update installer cache and results
         The path on the line above must exist at the root location to resolve
         this problem with your msi/msp file not being found or corrupted,
         In some cases you may need to manually copy the missing file or manually
         replace the problem file overwriting it is exist:
          Copy "\\Servername\ShareName$\SQL\SQL105\ENT\x64\setup\sql_engine_core_inst_msi\sql_engine_core_inst.msi" C:\Windows\Installer\91a4f43.msi
     It points to a location that doesn’t exist in the central server (servername) from where usually the installation media is present. The folder structures were re-arranged and the path mentioned (\\Servername\ShareName$\SQL\SQL105\ENT\x64\setup\sql_engine_core_inst_msi)
    is no longer there.
    Now from where do I copy this particular .MSI file? I've tried using search option but I'm unable to find it.
    One more update is that I was successfully able to do the SP3 upgrade on another server which was SQL Server 2008R2 SP2 (No CU on it)
    Hi Jayakrishna,
    After your above steps, please put the SQL Server setup media on the same path
    \\Servername\Sharename$\SQL, then run the VB script again and it will recreate the MSI file on the path C:\Windows\Installer with the name “91a4f43.msi“.
    If the error still occurs, then you can manually restore the missing MSI file following the steps of Procedure 2 in this article:
    http://support.microsoft.com/kb/969052 .
    In addition, we recommend you use local copy of media to install SQL Server 2008 R2 SP3.
    Thanks,
    Lydia Zhang

  • SQL Server 2008 Profiler--Templates Missing

    For some reason (even after an uninstall, reinstall and updating the the Community Update) there are no templates visible in the Profiler for SQL Server 2008. On another system it works fine but the Trace Provider Type shows "Microsoft SQL Server 2008". On the problem system it shows "Microsoft SQL Server 10.0".
    What's up?

    For some reason (even after an uninstall, reinstall and updating the the Community Update) there are no templates visible in the Profiler for SQL Server 2008. On another system it works fine but the Trace Provider Type shows "Microsoft SQL Server
    2008". On the problem system it shows "Microsoft SQL Server 10.0".
    What's up?
    Here is the actual answer you were all looking for:
    The server you are connecting to is a 10.50 sql server and your machine doesnt have a folder for that. So to fix it, copy your 100 folder (found: C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Profiler\Templates\Microsoft SQL Server\100) making a
    new folder in the same location named 1050.
    Everything will work fine now.

  • Creating dynamic database connection (SQL server 2008) from Adf application

    Hello,
    I am creating an ADF Fusion Application. I use Jdev. 11.1.2.3.0 , WebLogic 10.3 and MS SQL server 2008 database. My question is that how can I create a database connection configuration file, now I connect to the database through hard coding, there should be a way to do this with sql server I think.
    my database name is : testDatabase
    my database username is : testUser
    my database password is : testPassword
    Anybody can help me please.
    Thanks,
    Shahe

    Hello Frank,
    The database schema is the same for all the users, but the location of the database differs, for example: I have set the hostname of the database to localhost because the database is installed on the local pc, but to other clients the database is installed on a managed server so in the hostname I should put the server's ip address or name. So I need an external file where I can set these options.
    Thanks,
    Shahe

  • Sql server 2008 r2 setup support rules missing cluster node

    i have error on install sql r2 there are problems in cluster node its failed on windows 8

    Hi ,
    Before you install SQL Server on a computer that is running Windows 8, about Microsoft SQL Server 2008 , you must apply and install Microsoft SQL Server 2008 R2 Service Pack 1 or a later after the initial setup is complete. To install a SQL Server failover
    cluster, you must create and configure a failover cluster instance by running SQL Server setup. For more information, see:
    Installing a SQL Server 2008 R2 Failover Cluster: http://msdn.microsoft.com/en-us/library/ms179410(v=sql.105).aspx
    In addition, as other post, could you please help us to collect the detailed error message and the following error log? It is very useful for our research.
    C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\LOG\Summary.txt.
    C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\Detail.txt
    Regards,
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • Execute a procedure with a list of array in sql server 2008

    HI all,
    I have a procedure which has a list of values passed as an array . How can i execute my procedure with array list? how to implement this?Please help me.
    Thanks in advance
    Deepa

    Hi Deepa,
    basically Microsoft SQL Server does not support arrays as data types for procedures. What you can do is creating a type which represents a table definition. This type can than be used in a procedure as the following demo will show:
    The first script creates the environment which will be used for the execution
    -- 1. create the table as a type in the database
    CREATE TYPE OrderItems AS TABLE
    ItemId int PRIMARY KEY CLUSTERED
    GO
    -- 2. demo table for demonstration of results
    CREATE TABLE dbo.CustomerOrders
    Id int NOT NULL IDENTITY (1, 1) PRIMARY KEY CLUSTERED,
    CustomerId int NOT NULL,
    ItemId int
    GO
    -- 3. Insert a few records in demo table
    INSERT INTO dbo.CustomerOrders
    (CustomerId, ItemId)
    VALUES
    (1, 1),
    (2, 1),
    (3, 3),
    (1, 3);
    GO
    -- 4. Create the procedure which accepts the table variable
    CREATE PROC dbo.OrderedItemsList
    @Orders AS OrderItems READONLY
    AS
    SET NOCOUNT ON;
    SELECT o.*
    FROM dbo.CustomerOrders AS O INNER JOIN @Orders AS T_O
    ON (o.ItemId = T_O.ItemId);
    SET NOCOUNT OFF;
    GO
    The above script creates the table data type and a demo table with a few demo data. The procedure will accept the table data type as parameter. Keep in mind that table variable parameters have to be READONLY as parameter for procedures!
    The second script demonstrates the usage of the above scenario
    When the environment has been created the usage is a very simple one as you can see from the next script...
    -- 1. Fill the variable table with item ids
    DECLARE @o AS OrderItems;
    INSERT INTO @o (ItemId)
    VALUES
    (1), (3);
    -- 2. Get the list of customers who bought these items
    EXEC dbo.OrderedItemsList @Orders = @o;
    MCM - SQL Server 2008
    MCSE - SQL Server 2012
    db Berater GmbH
    SQL Server Blog (german only)

  • Why is the LookUp object in the Flow Task of my SSIS package going red (and not working) ? Sql Server 2008 R2

    I have been working with the Sql Server 2008 R2 SSIS Tutorial at
    https://msdn.microsoft.com/en-us/library/ms170419(v=sql.105).aspx
    --specifically -- Lesson 1.  I have been having some problems with this lesson where the source data from the samples download doesn’t exactly match the data described in the tutorial, and the tables in the tutorial are different from what
    is contained in AdventureWorksDW (tutorial refers to DimTime – AdventureWorksDW contains DimDate and no DimTime).  
    So, after futzing in BI with this tutorial  so that I can at least get it to run in Debug – it errors out on the 2<sup>nd</sup> LookUp object.
    Rather than looking for a fix to the problem(s) that I am having between the tutorial and the stuff I downloaded in the samples --
     I want “Adapt” the tutorial so I can use the stuff I downloaded and hopefully learn how to use SSIS with the elements (source data and tables) that are present on my workstation. 
    Here is a description of what is going on for me – which I really don’t understand what is going on in BI – based on the images below – like what columns (from what tables) are they associating to in the OleDB Destination? 
    Note:  the sql in the LookUps here is the sql that I copied from the tutorial. 
    I probably need to modify these sql statements – so -- the help I am requesting is to make the required modifications/changes
     so that I can adapt this tutorial with the stuff that’s on my workstation.
    I downloaded the samples and the AdventureWorksDW mdf for Sql Server 2008 R2. 
    It turns out that in the tutorial it wants me to select a DimTime table, but the version of the AdventureWorksDW db does not contain a DimTime table. 
    Instead, it contains a DimDate table.  So I tried adapting DimDate for the tutorial. 
    Additionally, the sample data file -- SampleCurrencyData.txt -- has slightly different data types than the types described in the tutorial, so I selected data types for the columns in the datasource text file that would work in BI would to
    connect column from source data file to the table.
    After finishing all the steps for Lesson 1 -- when I tried debugging the package – and it error'd out on  the 2<sup>nd</sup> Lookup object whichwent red.
      I edited the lookups and the sample Ole DB Destination to "ignore on fail” and I did all
     green but the FactCurrencyRate table is not being populated -- as described in the tutorial, so I reset the on error back to default (Fail on error option).   And based on this tutorial -- I believe FactCurrencyRate
    table is the table which is supposed to be populated with the data from SampleCurrencyData.txt?
    In the sample data file that downloaded with all the samples  I removed all the data from the text file except for 6 rows, so instead of the original 1100 or so rows, I have only 6 rows of data in the source data file (just to keep things
    simple for debugging for now).  I did not modify the data itself. 
    Here is what the (raw) data contained in SampleCurrencyData.txt looks like (from the samples that I downloaded from codeplex) – it’s supposed to be 4 columns of data – float, nvarchar, datetime, float:
    0.281690141       USD      
    6/26/2004 0:00  0.281713948
    0.281690141       USD      
    6/27/2004 0:00  0.281642539
    0.281690141       USD      
    6/28/2004 0:00  0.281761573
    0.283286119       USD      
    6/29/2004 0:00  0.283221933
    0.283286119       USD      
    6/30/2004 0:00  0.283358363
    0.281690141       USD      
    7/1/2004 0:00     0.281682206
    Below are images of my BI Layout for Lesson 1 from this tutorial -- the FlatFile and configurations for On Fail Error, A Flow task, the 2 LookUps (CurrencyKey and DataKey), the OleDB Destination configuration, the Design view of the associated tables and
    the Debug Run of Lesson 1, and the following error messages. My goal is to figure out what is going on in BI for this tutorial.
    Error: 0xC020901E at Extract Sample Currency Data, Lookup Datakey [51]: Row yielded no match during lookup.
    Error: 0xC0209029 at Extract Sample Currency Data, Lookup Datakey [51]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR. 
    The "component "Lookup Datakey" (51)" failed because error code 0xC020901E occurred, and the error row disposition on "output "Lookup Match Output" (53)" specifies failure on error. An error occurred on the specified
    object of the specified component.  There may be error messages posted before this with more information about the failure.
    Error: 0xC0047022 at Extract Sample Currency Data, SSIS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED. 
    The ProcessInput method on component "Lookup Datakey" (51) failed with error code 0xC0209029 while processing input "Lookup Input" (52). The identified component returned an error from the ProcessInput method. The error is specific
    to the component, but the error is fatal and will cause the Data Flow task to stop running. 
    There may be error messages posted before this with more information about the failure.
    --this is the flat file
     -- SampleCurrencyData.txt (which only contains 6 data rows for my purposes)
    --and here is where I assign the data types for the colums of -- SampleCurrencyData.txt
    This is the first LookUp Object -- LookUp Currency Key – The DB contains DimCurrency table. 
    I copied the sql from the tutorial here.
    I actually have a DimCurrency table in my copy of AdventureWorksDW. 
    Here’s the design view of DimCurrency and a sample of the data contained in DimCurrency and the On Fail configuration
    I actually have a DimCurrency table in my copy of AdventureWorksDW. 
    Here’s the design view of DimCurrency and a sample of the data contained in DimCurrency and the On Fail configuration
    --Here is what the data looks like in the DimCurrency table
    --2<sup>nd</sup> LookUp object  -- LookUp Data Key – this is the LookUp
     where BI errors out on Debug
    --it appears this lookup is referencing the DimDate table – which I DO have in the DB.
    --I can’t find the following sql in the tutorial, so I suppose BI added the sql (did it?)
    --Here's how I configured for On Error
    --Here is DimDate table in Design view
    --Here is a sample of the original data contained in DimData
    OleDB Destination
    --Here is where I get lost a bit – what is going on in the destination here?
    --Here's my On Error configuraino
    --and here is the FactCurrencyRate table
    --and here is a sample of the data contained in FactCurrencyRate
    Rich P

    Thank you for your reply.  I changed the error handling as you suggested on the 2nd lookup to redirect to unmatched rows.  Now I get all greet.  I don't have the conditional split as in your diagram.  But also, nothing appears to have
    happened in the DB.  Aren't the rows in my text file supposed to be added to the FactCurrencyRate table?
    How do I get a conditional split?
    Rich P
    OK, sorry I forgot to reply you back.
    Conditional Split was just dummy task. Ignore it.
    Manipulate the data in such way that you get matching records.
    Inside Source, for first 2 rows I put the dates which are available in DimDate.
    1.00010001,ARS,7/1/2005 0:00,0.99960016
    1.00010001,ARS,2/5/2006 0:00,1.001001001
    1.00020004,ARS,9/5/2001 0:00,0.99990001
    1.00020004,ARS,9/6/2001 0:00,1.00040016
    1.00050025,ARS,9/7/2001 0:00,0.99990001
    1.00050025,ARS,9/8/2001 0:00,1.001001001
    Then in OLE DB Destination, I loaded the rows to TestFactTable.
    (Now, you don't even need NO MATCH OUTPUT as there are matching records here)
    Cheers,
    Vaibhav Chaudhari
    [MCTS],
    [MCP]

  • "Value cannot be null" error when trying to edit or create Maintenance Plan in SQL Server 2008

    I have SQL Server 2008 installed on Windows Server 2008 64bit, every time I try to open or create a new Maintenance Plan I receive the error:
    Value cannot be null.
    Parameter name: component (System.Design)
    Program Location:
       at System.ComponentModel.Design.DesignerHost.System.ComponentModel.Design.IDesignerHost.GetDesigner(IComponent component)
       at Microsoft.DataTransformationServices.VsIntegration.DtsDesignerService.OpenDesigner(String connectionString, Object connection, String objectUrn)
       at Microsoft.SqlServer.Management.DatabaseMaintenance.MaintDesignerMenuHandler.Invoke()
    And in the Design view screen
    "Microsoft SQL Server Management Studio is unable to load this document: Could not load type 'Microsoft.SqlServer.Dts.runtime.Wrapper.IDTSPackageSigning100' from assembly 'Microsoft.SqlServer.DTSRunTimeWrap, Version=10.0.0.0, Culture=neutral'. 
    I have searched for a possible solution and have tried some suggestions of registering the msxml6.dll but and have installed VS2008 SP1 but I'm not in a position where I can do a full reinstall of SQL Server right now. Any help is appreciated. My SQL server
    environment information is below. 
    Microsoft SQL Server Management Studio
    10.0.1600.22 ((SQL_PreRelease).080709-1414 )
    Microsoft Analysis Services Client Tools
    2007.0100.1600.022 ((SQL_PreRelease).080709-1414 )
    Microsoft Data Access Components (MDAC)
    6.0.6002.18005 (lh_sp2rtm.090410-1830)
    Microsoft MSXML 3.0 4.0 5.0 6.0 
    Microsoft Internet Explorer 8.0.6001.18943
    Microsoft .NET Framework 2.0.50727.4206
    Operating System 6.0.6002

    I digged a little deeper and figured out it was a missing directory/file in %TEMP%. Seems some CleaningTool removes all files/directories in %Temp% and after that SSMS was not working any longer. The missing file is actually not needed, but the
    missing directory causes the "Value cannot be null" error.
    My missing file name was:
    C:\Users\<username>\AppData\Local\Temp\2\6vvdaozf.tmp
    But the file name changes on every startup.
    So my missing directory name was:
    C:\Users\<username>\AppData\Local\Temp\2
    After creating a empty directory with the name "2" in %TEMP% all went back to work fine for me.
    I'm not sure the directory name is every time the same, but you can discover your missing file with the process monitor from Sysinternal Tools and filters to "Process Name is ssms.exe" and "Path contains AppData\Local\Temp"
    Hope this helps other people to solve their issues too.
    Thank you!! When I run %temp% it takes me to "C:\Users\Admin ...~\AppData\Local\Temp\some random number". At first the random number was 3, after I logged off and back on it was 2. My temp variable in enviromental variables is correct. I looked on another machine
    running SQL2008 and temp is correct there. If I try to rename the numbered folder SSMS stops working. Any idea?

  • Crystal Report 13 Visual Studio 2010 SQL Server 2008 R2 ODBC Problem

    Hi Everybody,
    I am new in Crystal Report.
    I developed a web application in Visual Studio 2010, and my Database is SQL Server 2008 R2.
    I created reports using Crystal Report 13 in Visual Studio and my Operating System is Windows 7 32-Bit.
    I used ODBC Connection System DNS for my application.
    It is running fine even after Hosting on my local PC.
    But it creates problem when hosted on my Team Leader PC and Test Server.
    Their Configurations are same but only difference is "SQL Server 2008" Not R2
    The Error I am getting is "Failed to open the connection".
    When I Host the same on my another team member PC, I am getting the error like
    "Failed to open the connection. Details: [Database Vendor Code: 4060 ] Database Connector Error: ' [Database Vendor Code: 4060 ]' Failed to open the connection. Failed to open the connection. TestVr {CE268132-D2BD-43EC-BE45-0BCD847FBCDA}.rpt Details: [Database Vendor Code: 4060 ]"
    I tried various solution to fix this bug.
    But i am unable to do this and not getting any idea to fix this issue.
    If anyone can guide I will be thankful to him.
    All suggestions are appreciable.
    Thank you

    Hi,
    Please use the top right search box. for ex below search which will return many useful kb's, articlea and forum threads where simillar issues are discussed.
    [http://www.sdn.sap.com/irj/scn/advancedsearch?query=failedtoopentheconnection|http://www.sdn.sap.com/irj/scn/advancedsearch?query=failedtoopentheconnection]
    Most probably the issue is missing database client driver / provider.
    Install the driver used to connect the rpt to the db on the server and then create a 32 bit DSN with the same name as the dev machine..
    Hope this helps,
    Bhushan.

  • How to Configure Remote Connections To SQL Server 2008 R2 Express

    Post written June 10, 2010 and pertains to:
    SQL Server 2008 R2 Express on both my server and local machines: SQLX_SRV,
    SQLX_LOC
    SQL Server 2008 R2 Management Studio on both my server and local machines:
    MS_SRV, MS_LOC
    Windows Server 2008 R2 Enterprise installed on a Hyper-V VPS: WS
    SQL Server Configuration Manager on both my server and local machines:
    CMGR_SRV, CMGR_LOC
    Server Manager: SMGR
    I am connecting to my hosting server via Remote Desktop Connection: RDC
    I installed SQLX_SRV and MS_SRV on my hosting server and SQLX_LOC and MS_LOC on my local development machine.  I am able to use MS_LOC to connect to SQLX_LOC and to use MS_SRV to connect to SQLX_SRV.  However I am not able to use MS_LOC to connect
    with SQLX_SRV.  Here's what I have done so far:
    SMGR -> Configuration -> Windows Firewall to turn off the Windows Firewall for Domain, Private and Public profiles.  Obviously I'll change this later, but until I can connect I want to remove as many variables as possible.
    CMGR_SRV -> SQL Server Services to confirm that both SQL Server (SQLEXPRESS) and SQL Server Browser services were running.
    CMGR_SRV -> SQL Server Network Configuration -> Protocols for SQLEXPRESS to ENABLE the Shared Memory, Named Pipes, and TCP/IP protocols and DISABLE the deprecated VIA protocol.
    CMGR_SRV -> SQL Server Network Configuration -> Protocols for SQLEXPRESS -> double click TCP/IP to open the TCP/IP properties dialogue.  On the Protocol tab Enabled: Yes, Keep Alive: 30000, changed Listen All to No.  I've tried it both
    ways, but I've got six IP addresses on my server and I wanted to configure SQLEXPRESS to listen to only the first and primary IP.  On the IP Addresses tab went to IPALL and cleared the TCP Dynamic Ports field and entered 1433 in the TCP Port field. 
    For my first and primary IP Address I made sure that Enabled was Yes, I cleared the TCP Dynamic Ports field, and entered 1433 in the TCP Port field.  For all other IP Addresses Enabled was set to No and I cleared both the TCP Dynamic Ports and TCP Port
    fields.
    CMGR_SRV -> SQL Server Services -> SQL Server (SQLEXPRESS) right click and Restart.  This of course stopped and restarted my instance of SQLX_SRV enabling the TCP/IP configuration in the previous step to take effect.
    On my server, SQLX_SRV is the only instance of SQL Server running and so it's easy to hard wire it to the default port 1433.
    The instance name for both SQLX_SRV and SQLX_LOC is the default "SQLEXPRESS".  My server machine name is "SERVER1" on the EnglishBrains.com domain.  So the proper local name (local within the context of my remote server as connected via RDC) for
    my instance of SQLX_SRV would be:
    SERVER1\SQLEXPRESS 
    Note the use of a backslash NOT a forward slash. 
    Of course to connect remotely from my development machine, which is not on the same domain as my hosting server, I would need to specify the domain as well, so the SQL Server name becomes:
    SERVER1.EnglishBrains.com\SQLEXPRESS
    I must also use SQL Server Authentication.  Before I can use such a remote connection, however, there are still several configuration steps required.  So on my server (connected via RDC) I used MS_SRV to connect to SQLX_SRV using SERVER1\SQLEXPRESS
    for the server name and Windows Authentication.  Once connected I performed the following steps:
    MS_SRV -> right click the connected parent SERVER1\SQLEXPRESS instance node at the top -> Properties -> Security -> Server authentication: select "SQL Server and Windows Authentication mode".  This will enable connections using either type
    of authentication.
    Next, leaving the Server Properties dialogue open, Connections -> check "Allow remote connections to this server" box.
    Click OK to save these changes and close the Server Properties dialogue.
    MS_SRV -> Security -> right click Logins and select "New Login...", the Login - New dialogue opens.
    On the General page Enter a name for your new login
    Select SQL Server Authorization
    Enter and confirm a password
    Uncheck Enforce password expiration
    Select the default Database and Language
    On the ServerRoles page Public will be checked, also check SysAdmin.  This is probably not a good idea and I'll uncheck this as soon as I can connect to the SQLX_SRV.
    On the User Mapping page select the databases you want your new Login to access and enter the Default Schema of "dbo".
    At the bottom of the User Mapping page you'll see the Database Roles table.  Public will be selected by default.  Also select db_Owner.  Again this is probably not a good idea, and I'll refine this once I can connect.
    On the Status page confirm that "Grant" is checked under "Permission to connect to database engine" and "Enable" is checked under "Login".
    Click OK to save all changes and close the Login - New dialogue.
    With these steps completed you should now be able to use MS_SRV to connect to SQLX_SRV using SQL Server Authentication by supplying the name and password for your new Login.  I tried this and it worked fine.  Next I tried to use this same login
    remotely, that is I went to my local development machine and used MS_LOC to try and connect to SQLX_SRV by using
    SERVER1.EnglishBrains.com\SQLEXPRESS
    and opting for SQL Server Authentication and supplying the name and password of my new login.
    THIS DID NOT WORK??  Instead I get the following error message:
    Cannot connect to SERVER1.EnglishBrains.com\SQLEXPRESS.
    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider:
    SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1)
    For help, click:
    http://www.microsoft.com/products/ee/transform.aspx?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1
    If you follow the suggested help link, you are told:
    The SQL Server client cannot connect to the server.  This error could be caused by one of the following reasons:
    A specified SQL Server instance name is not valid.
    The TCP, or named pipes protocols are not enabled.
    The firewall on the server has refused the connection.
    The SQL Server Browser service (sqlbrowser) is not started.
    WRONG on all 4 counts!  The instance name IS valid.  Both TCP/IP and Named Pipes protocols are enabled.  The firewall has been shut down, so it is not relevant.  Finally the SQL Server Browser IS started.
    The next thing I tried was to circumvent discovery by the SQL Browser service by using the following syntax to specify the IP address and port directly when specifying the SQL Server name.
    tcp:68.71.134.186,1433
    Using this in the Server Name field I was able to use MS_SRV to successfully connect to SQLX_SRV (using SQL Server Authentication of course) with or without the SQL Browser service running. 
    However when I tried to connect from MS_LOC to SQLX_SRV using this same login (WITH SQL Browser service running just for good measure) it does not work??  I get the following error message:
    Cannot connect to tcp:68.71.134.186,1433.
    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider:
    TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) (Microsoft SQL Server, Error: 10060)
    For help, click:
    http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=10060&LinkId=20476
    If you follow the help link you are told:
    "The SQL Server client cannot connect to the server. This error could occur because either the firewall on the server has refused the connection or the server is not configured to accept remote connections."
    However, the firewall has been shut down and the server HAS been configured to accept remote connections! 
    I confirmed that i could indeed Ping to 68.71.134.186  and running NetStat -a |find /i "listening" on the server shows that the server is indeed listening at 68.71.134.186 Port 1433 -- which is why I was able to connect to SQLX_SRV using MS_SRV with
    tcp:68.71.134.186,1433 .
    IN SUMMARY: Even though I can connect to my SQLEXPRESS instance multiple ways from the server itself, I cannot connect remotely from my development machine! 
    If anyone can help me figure out why I would be very, very grateful!

    My two cents to help you out on c# code example to configure the remote sql server express.
    Hope it helps. It works, but you have to be extra carefull to read it all and setup the server configuration and netsh commands; also the port fowarding on the router.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    namespace sqlremoteconnection
    class Program
    static void Main(string[] args)
    // this is the local sql server connection
    // 192.168.1.101\SQLEXPRESS
    // now, the configuration for remote access:
    // activate SQL SERVER BROWSER - set it to start "automatic"; then START UP
    // SQL Server Configuration Manager
    // --> SQL SERVER BROWSER -> properties -> Service -> Start Mode -> automatic -> apply
    // --> Log On -> Start -> Ok
                // netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = all profile = CURRENT
                // netsh firewall set portopening protocol = UDP port = 1434 name = SQLPort mode = ENABLE scope = all profile = CURRENT
                // netsh advfirewall firewall add rule name = SQLPort dir = in protocol = tcp action = allow localport = 1433 remoteip = any profile = PUBLIC
                // netsh advfirewall firewall add rule name = SQLPort dir = in protocol = udp action = allow localport = 1434 remoteip = any profile = PUBLIC
    // VERY IMPORTANT FOR REMOTE ACCESS: you have to add the rules on port fowarding
    // on the router!!!
    // TCP: 1433
    // UDP: 1434
    // or just a personal port like TCP 31433/UDP 31434
    // read carefully the netsh commands above
    // server name: 123.132.24.177\SQLEXPRESS
    // server name: anyurl.myftp.org\SQLEXPRESS,1433 <<-- regular port
    // server name: anyurl.myftp.org\SQLEXPRESS
    // server name: anyurl.myftp.org\SQLEXPRESS,31433 <<-- WOW different PORT here!!!
    SqlConnection myConnection = new SqlConnection(
    "user id=sa;" +
    "password=password_goes_here!;" +
    "server=anyurl.myftp.org\\SQLEXPRESS,31433;" +
    //"Trusted_Connection=no;" +
    "database=database_name_here; " +
    "connection timeout=30");
    try
    myConnection.Open();
    catch (Exception e)
    Console.WriteLine(e.ToString());
    try
    SqlDataReader myReader = null;
    SqlCommand myCommand = new SqlCommand("select * from mytable", myConnection);
    myReader = myCommand.ExecuteReader();
    while (myReader.Read())
    Console.WriteLine(myReader["tab01_name"].ToString());
    Console.WriteLine(myReader["tab01_age"].ToString());
    catch (Exception e)
    Console.WriteLine(e.ToString());
    try
    myConnection.Close();
    catch (Exception e)
    Console.WriteLine(e.ToString());
    Adelino Araujo

Maybe you are looking for

  • How to create a table with strings active by boolean button

    Good morning. I have a problem to create a table and did not find any topic in the forum who could help me solve this problem. I need to create an alarm table. That is, every time an alarm was activated (boolean button), the table will show the time,

  • Forcing a Group Header to Print

    Post Author: despec CA Forum: General I'll tell you, CR really can be very difficult to play with.  I have two files--one a Milestone File, another an Assignment File...The one-to-many is from the Milestine file to the Assignment file.  I am grouping

  • Why do security updates change my Firefox appearance

    If changing from FF28 to FF29 is for security reasons why does my FF appearance also change as it has nothing to do with security. Is it because some developers think it might be better this way or is there a security problem. I have now told FF not

  • INFORECORD PRICES SHOULD NOT BE CHANGED IN PO

    Sir, INFORECORD PRICES SHIOULD NOT BE ABLE TO CHANGE IN PO. REGARDS AMEY

  • Help download photos on an old cd, made before Lion and older version of iPhoto

    I have a MacBook Pro and I was trying to add some old photos from a CD that I had burned several years ago.  I now have Lion, which was not what I had on my computer when cd's were burned.  Also I used a different version of IPhoto. What do I have to