Olap vs sql

hi olap guys
i have a question
i am working on olap application on oracle9i R2 DW, i built the data warehouse and did ETL process now i am confused why i need to build my olap application to use olap api although i can do all queries
using sql (including cube,rollup,rank .... )statements using fact,dimensions tables incuding ( materialized views and dimensions objects for query rewriter) instead of olap api and olap metadata , what olap api can do for olap that i can't do it using oracle sql.
and what i should do to use forcasting,what-if analysis with my olap application.
thanks

I bet you will get hundreds of replies on this topic. I will try to summarize in short as much as possible.
If I understand correctly, your question is why should I build Analytical Workspaces (Oracle OLAP objects), when I can get most of the results using SQL statements with MVs?
Theoretically, you can do most of these stuff in SQL and whether you should build OLAP objects or not depends on what kind of application you are planning to build.
For example, if your reports are straight forward and do not include higher level of analytic, such as forecasting, complex calculations, time series (lead, lag) and year to date calculations then you may be ok to use the star schema (snowflake will also be ok). Also, if your data is highly sparse (there are no fact data for most of the dimension value combinations) you may be better of in relational world.
Now consider this scenario, you want to run reports which tell what would be the forecasted profit based on the historical data, market conditions/seasonality and you want to know 'how was your sales in this year/qtr compare to past couple of years/qtrs, or if you want to know, which of the top 5 products that are purchased by top 10 customers in geography that has sales growth more then 20% annually?' You will need AWs to answer these questions.
The Materialized views can only give you the aggregation data in a relational format,where as the AWs can give the aggregation in multidimensional format and will also provide you all the inbuilt calculations that are useful for analytical reporting.
Now, if you have decided to go for AWs, we can see how to built forecasting application and what-if analysis. Let us know.
Thanks

Similar Messages

  • Do we need to create ODBC connection on sql server-cube for OLAP connection?

    need to create olap connection sql server cube .....?

    Hi Wafa,
    Thanks for quick reply.
    Actually i don't have username or password.if you don't mind can you share me the document of this thread: 1623999 - How to make a connection to Microsoft SQL Server Analysis
    Services in Business Objects Enterprise 4.0
    please i want to fixed this issues so help me
    Regards
    Mustafa

  • T-SQL: Cursor is not advancing to next record

    SQL Version:  2008 R2
    Problem:  I have the code below which uses a cursor.  The cursor keeps returning the first record and does not advance to the next record in the cursor.  It appears as if the Fetch Next is not being recognized.  The Select
    Statement in the cursor declaration returns two records which is the result set I expect to be contained in the cursor record set.
    ...bob sutor
    SQL CODE:
    DECLARE
      @ProcessGroupID nchar(4)
     , @RemoveAuditUser nchar(128)
    DECLARE CertGroupCursor CURSOR FOR
     SELECT DISTINCT CertGroups.GroupCode, CertGroups.RemoveAuditUser
         --, UserControl.ProcessGroupID, UserControl.VPUserName
     FROM udCertGroups AS CertGroups
      LEFT JOIN udAuditUsers AS UserControl
      ON CertGroups.GroupCode = UserControl.ProcessGroupID
     WHERE CertGroups.GroupCode = UserControl.ProcessGroupID
      AND CertGroups.RemoveAuditUser = UserControl.VPUserName
    OPEN CertGroupCursor
     FETCH NEXT FROM CertGroupCursor INTO @ProcessGroupID, @RemoveAuditUser
     WHILE @@FETCH_STATUS = 0
     Print @ProcessGroupID + '-' + @RemoveAuditUser
     DELETE FROM udAuditUsers
      WHERE ProcessGroupID = @ProcessGroupID
       AND VPUserName = @RemoveAuditUser
     FETCH NEXT FROM CertGroupCursor INTO @ProcessGroupID, @RemoveAuditUser
    CLOSE CertGroupCursor
    DEALLOCATE CertGroupCursor
    Bob Sutor

    The real question is how to get rid of this mess. Think about the local “@remove_audit_user” as a variable; it's name is a verb, not a noun! and the NVARCHAR(n) lets you use Chinese Unicode. Why? In ISO-11179 rules , “remove_” is a called a role, and the
    audit user would be the attribute with the attribute property “_user” in a valid data model. Where is the table that models “audit_users”? It has to be here by definition. 
    One of the first rules of data modeling is that a data element has one and only one name. This is a results of the Law of Identity in Logic (A is A: to be is to be something in particular, to be nothing in particular or many things in general is to be nothing
    at all). 
    So how did “G.remove_audit_user = U.vp_user_name” occur??  ANSWER: lack of a design!
    Your “G.group_code = U.process_group_id” is wrong. An identifier is not a code! TOTALLY DIFFERENT type of data elements! Do you have a postal code or a postal id? Blood_type or blood_id?  Etc.? Have you ever read a book on basic data modeling? 
    The purpose of PRINT is debugging and not output. We had  joke in the ANSI X3H2 Committee that SQL means “scarcely Qualified as a Language” because there is no I/O. PRINT will screw up performance in so many ways. 
    In a properly designed schema, we seldom use SELECT DISTINCT; we have keys and a valid schema that does not produce redundant duplicate rows. It might be valid, but after 30+ years of SQL, I would bet against it. 
    Your statement would use an EXISTS() predicate to handle multiple columns and conditions. But you did not bother with DDL, as required by basic Netiquette, so here is the skeleton I can give you. 
    DELETE FROM UD_Audit_Users
     WHERE EXIST
           (SELECT *
              FROM UD_Cert_Groups AS G
             WHERE G.process_group_id = ?? 
               AND G.vp_user_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

  • T-sql case statement in a select

    When I execute the following t-sql 2012 statement, the "NO Prod' value is not
    being displayed from the sql listed below:
    SELECT DISTINCT
    IsNull(cs.TYPE,'') as type,
    CASE IsNull(Course.TYPE,'')
    WHEN 'AP' then 'AP Prod'
    WHEN 'IB' then 'IB Prod'
    WHEN 'HR' then 'HR Prod'
    WHEN '' then 'NO Prod'
    END AS label
    FROM CustSection cs
    INNER JOIN dbo.Person p on P.personID = cs.personID
    Left join customCustomer cs564 on cs564.personID = p.personID and
    cs564.attributeID ='564'
       where ( cs.type is null and cs564.attributeID = null)    
         or
        (cs.type IN ('HR','AP') OR
          (cs.type='IB' AND SUBSTRING(cs.code,1,1)='3'))  
    ORDER BY label
    What I want is for 'NO Prod' to be displayed when
    cs.type is null and cs564.attributeId  is null.
    Thus can you tell me how to fix query above so the 'NO Prod'  value is displayed in the
    select statement listed above?

    There is no CASE statement in SQL; we have a CASE expression. We do not use the old 1970's Sybase*- ISNULL(); we have  COALESCE().
    There is no such thing as a magic generic “type” in RDBMS. There is no such thing as a generic “code” in RDBMS. They have to to be “<something in particular>_type” and “<something in particular>_code” in a valid data model. How about blood_type
    and postal_code?? 
    There is no such thing as a generic “person” table in RDBMS. First of all, do you really have only one person, as you said?? But the important point is that these persons play a role in the data model – customers, students, etc. You are doing the wrong thing
    and doing it badly.  This table should not exist any more than a  table of “Things” such exist. 
    And the reason you are beyond any real help is “attribute_id” which tell us that your schema is a total disaster of data and meta data mixed together in a non-RDBMS written in awful SQL. Based on cleaning up bad SQL for 30 years, it looks like you are an OO
    programmer who never unlearned his prior mindset. 
    Why did you allow an encoding schema with blanks? Why do you have so many NULL-able columns? 
    SELECT DISTINCT is very rare in a properly designed schema. The DRI references assure that rows cam be matched. To get you started, look at this skeleton:
    CREATE TABLE Products
    (product_gtin CHAR(15) NOT NULL PRIMARY KEY, 
     product_type CHAR(2) DEFAULT 'XX' NOT NULL
      CHECK (product_type IN ('AP', 'IB', 'HR', 'XX'))
    The table name is a plural noun because it models a set (NOT an OO class).
    The GTIN is an industry standard identifiers, and not have to invent our own.
    The product_type (not blood_type, not automobile_body_type!) has a constraint that assures it is never NULL and never blank; I invented 'XX' as a default. 
    You need more help than you can get in a forum, but if you will follow Netiquette and post the DDL, we can get you started.
    --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

  • Benefit and limitation of temp table in sql server 2008

    I have a datagrid in front end of asp.net . when user select a row it shows another gridview (multiple row ) where user have to put some data. when user click CLOSE button  i have to keep all data of 2nd gridview in reference with 1st gridview row id. 
    Same process for each row of 1st gridview. If i will keep all the record in a datatable in view state and finally save the data in database table when final save is clicked then the process may be very slow due to large data in view state. So i think to store
    data in temp datable in database for each CLOSE click. For this porpose which temp table i should use
    1. Local temporary tables
    2. Global temporary tables
    3. Normal tables.
    Multiple user may do the same thing same time.  Please help me.
    Thanks

    >1. Local temporary tables
    >2. Global temporary tables
    >3. Normal tables.
    When used in stored procedures, local temporary tables (#table) are automatically multi-user.
    For global temp (##table) & normal tables, you need to develop your own mult-user logic.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • SQL Query to calculate on-time dispatch with a calendar table

    Hi Guys,
    I have a query (view) to calculate orders' fulfillment leadtimes.
    The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name
    isBusinessDay but I don't know how to best use this table to calculate the On-Time metric. I have been looking everywhere but so far I have been unable to solve my problem.
    Please find below the current calculation for the On-Time Column:
    SELECT
    Week#
    , ClntGroup
    , CORD_DocumentCode
    , DESP_DocumentCode
    , Cord_Lines --#lines ordered
    , CORD_Qty --total units orderd
    , DESP_Lines --#lines dispatched
    , DESP_Qty --total units dispatched
    , Status
    , d_status
    , OpenDate --order open date
    , DateDue
    , DESP_PostedDate --order dispatched date
    , DocType
    , [Lead times1]
    , [Lead times2]
    , InFxO
    , OnTime
    , InFxO + OnTime AS InFullAndOneTime
    , SLADue
    FROM (
    SELECT
    DATEPART(WEEK, d.DateOpn) AS Week#
    , Clients.CustCateg
    , Clients.ClntGroup
    , d.DocumentCode AS CORD_DocumentCode
    , CDSPDocs.DocumentCode AS DESP_DocumentCode
    , COUNT(CORDLines.Qnty) AS Cord_Lines
    , SUM(CORDLines.Qnty) AS CORD_Qty
    , COUNT(CDSPLines.Qnty) AS DESP_Lines
    , SUM(CDSPLines.Qnty) AS DESP_Qty
    , CDSPLines.Status
    , d.Status AS d_status
    , d.OpenDate
    , d.DateDue
    , CDSPDocs.PostDate AS DESP_PostedDate
    , d.DocType
    , DATEDIFF(DAY, d.OpenDate, d.DateDue) AS [Lead times1]
    , DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) AS [Lead times2]
    , CASE WHEN SUM(CORDLines.Qnty) = SUM(CDSPLines.Qnty) THEN 1 ELSE 0 END AS InFxO --in-full
    --On-Time by order according to Despatch SLAs
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales', 'Mail Order')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2 ) <= 2)
    THEN 1
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - USA')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2) <= 14)
    THEN 1
    WHEN Clients.ClntGroup = 'Export Market' OR Clients.CustCateg = 'UK Transfer'
    AND d.DateDue >= CDSPDocs.PostDate
    THEN 1
    ELSE 0
    END AS OnTime
    --SLA Due (as a control)
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales','Mail Order') AND CDSPDocs.PostDate is Null
    THEN DATEADD(DAY, 2 , d.OpenDate)
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - UK', 'Export Market - USA') OR (Clients.CustCateg = 'UK Transfer')
    AND CDSPDocs.PostDate IS NULL
    THEN DATEADD (DAY, 14 , d.OpenDate)
    ELSE CDSPDocs.PostDate
    END AS SLADue
    FROM dbo.Documents AS d
    INNER JOIN dbo.Clients
    ON d.ObjectID = dbo.Clients.ClntID
    AND Clients.ClientName NOT in ('Samples - Free / Give-aways')
    LEFT OUTER JOIN dbo.DocumentsLines AS CORDLines
    ON d.DocID = CORDLines.DocID
    AND CORDLines.TrnType = 'L'
    LEFT OUTER JOIN dbo.DocumentsLines AS CDSPLines
    ON CORDLines.TranID = CDSPLines.SourceID
    AND CDSPLines.TrnType = 'L'
    AND (CDSPLines.Status = 'Posted' OR CDSPLines.Status = 'Closed')
    LEFT OUTER JOIN dbo.Documents AS CDSPDocs
    ON CDSPLines.DocID = CDSPDocs.DocID
    LEFT OUTER JOIN DimDate
    ON dimdate.[Date] = d.OpenDate
    WHERE
    d.DocType IN ('CASW', 'CORD', 'MORD')
    AND CORDLines.LneType NOT IN ('Fght', 'MANF', 'Stor','PACK', 'EXPS')
    AND CORDLines.LneType IS NOT NULL
    AND d.DateDue <= CONVERT(date, GETDATE(), 101)
    GROUP BY
    d.DateOpn
    ,d.DocumentCode
    ,Clients.CustCateg
    ,CDSPDocs.DocumentCode
    ,d.Status
    ,d.DocType
    ,d.OpenDate
    ,d.DateReq
    ,CDSPDocs.PostDate
    ,CDSPLines.Status
    ,Clients.ClntGroup
    ,d.DocumentName
    ,d.DateDue
    ,d.DateOpn
    ) AS derived_table
    Please find below the DimDate table
    FullDateNZ HolidayNZ IsHolidayNZ IsBusinessDay
    24/12/2014 NULL 0 1
    25/12/2014 Christmas Day 1 0
    26/12/2014 Boxing Day 1 0
    27/12/2014 NULL 0 0
    28/12/2014 NULL 0 0
    29/12/2014 NULL 0 1
    30/12/2014 NULL 0 1
    31/12/2014 NULL 0 1
    1/01/2015 New Year's Day 1 0
    2/01/2015 Day after New Year's 1 0
    3/01/2015 NULL 0 0
    4/01/2015 NULL 0 0
    5/01/2015 NULL 0 1
    6/01/2015 NULL 0 1
    This is what I get from the query:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 0
    52 Web Sales 123457 24/12/2014 30/12/2014 0
    52 Web Sales 123458 24/12/2014 29/12/2014 0
    52 Local Market 123459 24/12/2014 29/12/2014 0
    1 Web Sale 123460 31/12/2014 5/01/2015 0
    1 Local Market 123461 31/12/2014 6/01/2015 0
    As the difference between the dispatched and open date is 2 business days or less, the result I expect is this:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 1
    52 Web Sales 123457 24/12/2014 30/12/2014 1
    52 Web Sales 123458 24/12/2014 29/12/2014 1
    52 Local Market 123459 24/12/2014 29/12/2014 1
    1 Web Sale 123460 31/12/2014 5/01/2015 1
    1 Local Market 123461 31/12/2014 6/01/2015 1
    I am using SQL Server 2012
    Thanks
    Eric

    >> The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name “isBusinessDay” but I don't know how to best use this table to calculate the On-Time metric. <<
    The Julian business day is a good trick. Number the days from whenever your calendar starts and repeat a number for a weekend or company holiday.
    CREATE TABLE Calendar
    (cal__date date NOT NULL PRIMARY KEY, 
     julian_business_nbr INTEGER NOT NULL, 
    INSERT INTO Calendar 
    VALUES ('2007-04-05', 42), 
     ('2007-04-06', 43), -- good Friday 
     ('2007-04-07', 43), 
     ('2007-04-08', 43), -- Easter Sunday 
     ('2007-04-09', 44), 
     ('2007-04-10', 45); --Tuesday
    To compute the business days from Thursday of this week to next
     Tuesdays:
    SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
     FROM Calendar AS C1, Calendar AS C2
     WHERE C1.cal__date = '2007-04-05',
     AND C2.cal__date = '2007-04-10'; 
    We do not use flags in SQL; that was assembly language. I see from your code that you are still in a 1960's mindset. You used camelCase for a column name! It makes the eyes jump and screws up maintaining code; read the literature. 
    The “#” is illegal in ANSI/ISO Standard SQL and most other ISO Standards. You are writing 1970's Sybase dialect SQL! The rest of the code is a mess. 
    The one column per line, flush left and leading comma layout tells me you used punch cards when you were learning programming; me too! We did wrote that crap because a card had only 80 columns and uppercase only IBM 027 character sets. STOP IT, it make you
    look stupid in 2015. 
    You should follow ISO-11179 rules for naming data elements. You failed. You believe that “status” is a precise, context independent data element name! NO! 
    You should follow ISO-8601 rules for displaying temporal data. But you used a horrible local dialect. WHY?? The “yyyy-mm-dd” is the only format in ANSI/ISO Standard SQL. And it is one of the most common standards embedded in ISO standards. Then you used crap
    like “6/01/2015” which is varying length and ambiguous that might be “2015-06-01” or “2015-01-06” as well as not using dashes. 
    We need to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. 
    And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> Please find below the current calculation for the On-Time Column: <<
    “No matter how far you have gone down the wrong road, turn around”
     -- Turkish proverb
    Can you throw out this mess and start over? If you do not, then be ready to have performance got to hell? You will have no maintainable code that has to be kludged like you are doing now? In a good schema an OUTER JOIN is rare, but you have more of them in
    ONE statement than I have seen in entire major corporation databases.
    --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

  • How to send the output of a script to a txt or rpt file using T-sql?

    Hi!
    I have some code which we use to record info about a database when we decommission it. I normally click Query > Results to File and then run it to produce a file.  I need to do this via t-sql so I can automate it. Any idea what code I need to make
    this script output to file?
    Thanks,
    Zoe
    SET NOCOUNT ON
    DECLARE @Databasename varchar(50)
    DECLARE @date as char(10)
    DECLARE @session_usr nchar(30);
    SET @Databasename = db_name()
    SET @date = convert(char(10), getdate(), 121)
    SET @session_usr = SYSTEM_USER;
    DECLARE @sqlCommand varchar(1000)
    select current_user
    Print '================================================================================'
    Print '========== SQL Decommission Report for '+ @@SERVERNAME +' ========='
    Print '========== Executed on ' + @date +' by '+ rtrim(@session_usr) +' ========='
    Print '================================================================================'
    Print ' '
    Print 'Database properties'
    Print '----------------------------------'
    select substring(name,1,25) as Name,substring(filename,1,40) as File_Name,cmptlevel as Compatibility_level from master.dbo.sysdatabases
    where name = @databasename
    Print 'Full Text Catalogs'
    Print '----------------------------------'
    select substring(name,1,20)as Name,status,substring(path,1,52) as Path FROM [master].[dbo].[sysfulltextcatalogs]
    Print 'SSIS Packages'
    Print '----------------------------------'
    IF (select cast(@@version as varchar)) like '%2012%' begin
    print 'sql 2012 instance'
    select substring(name,1,20) as Name,substring(description,1,40) as Description,ownersid as Owner from msdb.dbo.sysssispackages
    end else if (select cast(@@version as varchar)) like '%2008%' begin
    print 'sql 2008 instance'
    select substring(name,1,20) as Name,substring(description,1,40) as Description,ownersid as Owner from msdb.dbo.sysssispackages
    select substring(name,1,20) as Name,substring(description,1,40) as Description,substring(owner,1, 18) as Owner from msdb.dbo.sysdtspackages
    end else if (select cast(@@version as varchar)) like '%2005%' begin
    print 'sql 2005 instance'
    select substring(name,1,20) as Name,substring(description,1,40) as Description,suser_sname(ownersid) as Owner from msdb.dbo.sysdtspackages90
    select substring(name,1,20) as Name,substring(description,1,40) as Description,substring(owner,1, 18) as Owner from msdb.dbo.sysdtspackages
    end
    Print 'Linked Servers'
    Print '----------------------------------'
    SELECT substring(srvname,1,35) as LinkedServer_Name,substring(datasource,1,35) as Data_Source FROM master.dbo.sysservers WHERE isremote = 0
    Print 'Replication'
    Print '----------------------------------'
    IF (select count(*) from master.dbo.sysdatabases where name = 'Distribution') > 0
    select substring(publisher_db,1,20) as Published_DB,substring(Description,1,40) as Description from distribution.dbo.MSpublications
    ELSE print 'No replication'
    Print ' '
    Print 'Database Mail'
    Print '----------------------------------'
    SELECT substring(name,1,20) as Name,enabled,substring(email_address,1,35) as Email_address,last_email_date FROM msdb.dbo.sysoperators
    where last_email_date > dateadd(day,-30,getdate())-- detect whether any of the systems have sent an email in the last 30 days
    Print 'CLR Assemblies'
    Print '----------------------------------'
    select substring(Name,1,20) as Name,substring(Type_desc,1,35) as Description,Create_date from sys.objects where object_id in (select object_id from sys.assembly_modules)
    Print 'Logins'
    Print '----------------------------------'
    SET @sqlCommand = 'select substring(name,1,40) as Name,substring(dbname,1,30) as Default_Database from master.dbo.syslogins where sid in (select sid from '+ @databasename +'.dbo.sysusers where issqlrole <> 1 and hasdbaccess <> 0 and name <> ''dbo'')'
    EXEC (@sqlCommand)

    You can use bcp to export from database to flat file.
    It requires xp_cmdshell to work from a stored procedure.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Two digit year cutoff in SQL Server 2008 R2

    Hi All,
    We have a 2008R2 setup here and have SSIS jobs importing data from flat files into our database. Some sources only give us 2 digit years unfortunately. 
    Looking at some data, the default 2 digit year cutoff  is not really appropriate to our setup, a value of 2080 would be better. However, when checking the official documentation here:
    http://msdn.microsoft.com/en-us/library/ms191004(v=sql.105).aspx
    there is a warning to leave the value alone to maintain backwards compatibility. This warning is NOT present for the newer versions of SQL Server. Is this just a generic warning about the general application landscape, or is there some Microsoft code somewhere
    within SQL Server/SSIS/SSRS which assumes this default is locked to 2049? In other words, if I understand the application landscape at my office - am I safe to change this? Or is there some underlying code which will break?
    Also, am I right in the assumption that once a 2 digit year is imported into a database table, it's then converted to a 4 digit year, so any existing data is "safe" from this setting being changed? In other words, the DB loses all memory of whether
    an imported date was originally imported as a 2 digit year?
    Thanks

    Import the string dates into DATE/DATETIME format.
    DATE/DATETIME has 4 digit year.
    You can convert it differently than the automatic 2049 flip year.
    DATE/TIME functions & string conversions:
    http://www.sqlusa.com/bestpractices/datetimeconversion/
    Here is an automatic conversion example.
    DECLARE @StringDate char(8) = '10/23/80';
    DECLARE @Date DATE;
    SELECT @Date=CONVERT(date, @StringDate, 1);
    SELECT @Date;
    -- 1980-10-23
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • Pass unicode data in SQL Server 2008 stored procedure parameter

    Hi,
    I want to pass unicode data in a SQL stored procedure. But I am not sure that how to append N with NVarchar datatype.
    For example I Create a table LocalizationTest and wants to insert a few records.
    Create table LocalizationTest
        Field1 NVarchar(255)
    INSERT INTO LocalizationTest
    VALUES(N'123 Illini Dr, 東皮奧里亞, 8989')
    the above given statement works.
    To explain it more , script A works but script B does not work.
    DECLARE @X NVARCHAR(255)
    [A]
    SET @X=N '123 Illini Dr, 東皮奧里亞, 8989'
    INSERT INTO LocalizationTest
    VALUES(@X)
    [B]
    SET @X= '123 Illini Dr, 東皮奧里亞, 8989'
    INSERT INTO LocalizationTest
    VALUES(@X)
    What is the correct way to execute script B because @X will be passed in a SQL Stored Procedure?
    Thanks
    Sharma M.

    If you do not pass the value as a Unicode value there is nothing left of the Unicode characters but question marks. Once this has happened, AFAIK there is no way to undo it (other than resetting the value as Unicode characters again).
    Affirmative.
    Demo - This is what happens if you convert UNICODE (nvarchar) to varchar with implicit conversion (try to force 2 bytes into one byte).
    3F hex is '?'.
    CREATE TABLE #LocalizationTest (Field1 VARCHAR(255))
    INSERT INTO #LocalizationTest
    VALUES(N'123 Illini Dr, 東皮奧里亞, 8989')
    DECLARE @X NVARCHAR(255), @dSQL NVARCHAR(MAX)
    SET @X=N'123 Illini Dr, 東皮奧里亞, 8989'
    INSERT INTO #LocalizationTest VALUES(CONVERT(NVARCHAR(255),@X))
    SET @dSQL = N'INSERT INTO #LocalizationTest VALUES(N'''+@X+''')'
    PRINT @dSQL
    EXEC sp_ExecuteSQL @dSQL
    SELECT *, Field1Bin=convert(binary(30), Field1) FROM #LocalizationTest
    DROP TABLE #LocalizationTest
    123 Illini Dr, ?????, 8989 0x31323320496C6C696E692044722C203F3F3F3F3F2C203839383900000000
    123 Illini Dr, ?????, 8989 0x31323320496C6C696E692044722C203F3F3F3F3F2C203839383900000000
    123 Illini Dr, ?????, 8989 0x31323320496C6C696E692044722C203F3F3F3F3F2C203839383900000000
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Rolling Averages in Sql Server 2008

    I dint get the perfect answer last time and i am still working on the exact output that i need.
    I have the two integer columns in my table and i have to calculate averages for those two columns.Hence my output should be 
    date col1 col2 AVGcol1 AVGcol2
    and the average of each row should be avg(value of current date and sum of last five date). In this case i have more than one row for a single date.That also needs to be considered.
    Thanks in Advance!!!!!!

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> I did not get the perfect answer last time and I am still working on the exact output that I need. <<
    Perhaps you might consider posting DDL and giving us sample date, so we can do your job for you?
    >> I have the two integer columns in my table and I have to calculate averages for those two columns. Hence my output should be 
    something_date, col1, col2, col1_avg, col2_avg
    and the average of each row should be avg(value of current date and sum of last five dates). In this case I have more than one row for a single date. That also needs to be considered.<<
    I might have guessed that the generic date was the key, but your narrative says this is not so. Too bad we have no idea what the key might be. Too bad we have no idea about NULLs, either! Why did we have to almost torture you to get anything? Just give us DDL
    at the start. 
    CREATE TABLE Garbage 
    (posting_date DATE NOT NULL, 
     col_1 INTEGER NOT NULL, 
     col_2 INTEGER NOT NULL, 
     PRIMARY KEY (???));
    INSERT INTO Garbage 
    VALUES
    ('2014-12-10', 250, 200), 
    ('2014-12-21', 100, 100), 
    ('2014-12-21', 150, 300), 
    ('2014-12-21', 100, 100), 
    ('2014-12-22', 150, 300), 
    ('2014-12-23', 100, 100), 
    ('2014-12-23', 150, 300), 
    ('2014-12-24', 100, 100), 
    ('2014-12-24', 150, 300), 
    ('2014-12-25', 200, 450); 
    Here is my guess: sum up each day's postings into G2. Now t34eh date could be a key! Then use G2 with a windows clause to get the prior 5 rows. That is not quite the same as the prior five
    days, however, if we have gaps. The RANGE option does not work completely in T-SQL, but we could do an outer join to a calendar table and some other tricks.
    WITH G2(posting_date, col_1, col_2)
    AS
    (SELECT posting_date, SUM(col_1), SUM(col_2) 
     FROM Garbage
    GROUP BY posting_date)
    SELECT posting_date, 
     col_1,
     AVG(col_1 * 1.00)
     OVER (ORDER BY posting_date 
     ROWS BETWEEN 5 PRECEDING AND CURRENT ROW)
     AS col1_avg, 
     col_2,
    AVG(col_2 * 1.00)
     OVER (ORDER BY posting_date 
     ROWS BETWEEN 5 PRECEDING AND CURRENT ROW)
     AS col2_avg
     FROM G2; 
    --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

  • How to improve SQL table perfomance

    Hi,
    I have one table having 5lacks recording during the select operation the query is very slow. The table is in third normal form having primary key and index.Is there any other way to improve table performance....

    Generally consider indexing ON clause and WHERE clause columns.
    Also make sure the WHERE clause predicates are SARGable:
    http://www.sqlusa.com/bestpractices/sargable/
    Optimizaton: http://www.sqlusa.com/articles/query-optimization/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • SQL CASE STATEMENT IMPLEMENTATION

    REquirment
    • Add indicator to the end of the files, (position 1051 in both extracts, either have value of Y or N).
    o DUAL COVERAGE (Y/N)
    • Logic to determine indicator values from Member Eligibility Table:
    o For ‘Y’ indicator:
    o When dbo. CMC_MEPE_PRCS_ELIG.CSCS_ID = ‘MD11’ (Mean Dual covered member)
    o For ‘N’ indicator:
     When dbo. CMC_MEPE_PRCS_ELIG.CSCS_ID <> ‘MD11’
    • Groups included:
    o 100100 (Medicare)
    o 100598 (Medicaid-OHP)
    • Previous syntax
    • select top 20000
    • EXT_DATE,SUPPLIER_NAME,BUSINESS_UNIT,PROG_NO,PG_DESC,DIVISION_NO,RISKPOP_MEDICARE_EVENT_CODE,
    • RISKPOP_MEDICAID_AID_CATEGORY,MEMBER_NO,MEDICARE_NO,MEDICAID_NO,LASTNAME,MIDINITIAL,FIRSTNAME,YMDBIRTH,
    • a.SEX,CLASS,CL_DESC,S_LASTNAME,S_MIDINITIAL,S_FIRSTNAME,S_DOB,S_SEX,BENFIT_PKG,BEN_PKG_DESC,CLASS_ID,PLAN_ID,
    • YMDEFF_BP,YMDEND,REASON,PRIME_SECOND,PHP_DUAL,S_ADDRESS1,S_ADDRESS2,S_ADDRESS3,S_CITY,S_STATE,S_ZIP,S_COUNTRY,
    • S_PHONE,M_ADDRESS1,M_ADDRESS2,M_ADDRESS3,M_CITY,M_STATE,M_ZIP,M_COUNTRY,M_PHONE,DIV_NAME,PROV_NO,IRS_NO,
    • P_LASTNAME,P_FIRSTNAME,P_MIDINITIAL,YMDEFF_PCP,ALT_KEY,ALT_CARRIER_NO,ALT_CARRIER_FUL,ALT_YMDEFF,ALT_YMDEND,
    • BENFIT_PKG_EFF,BENFIT_PKG_TERM,a.MEME_CK,
    • b.HIOS_NUMBER,
    • null as PREMIUM_PAID_DATE,
    • null as PREMIUM_PAID_END_DATE,
    • b.APTC,
    • null as 'GracePeriodIndicatorStartDate',
    • null as'GracePeriodIndicatorEndDate',
    • null as'ExchangePlanType'
    • from Extract_602_603_PBH_Extract_Main a
    • left join Extract_602_603_PBH_Extract_HRI b
    • on LEFT(a.MEMBER_NO,7) = b.SBSB_ID
    Syntax I am trying to implement(taking forever to execute) Please help correct
    select distinct
    EXT_DATE,SUPPLIER_NAME,BUSINESS_UNIT,PROG_NO,PG_DESC,DIVISION_NO,RISKPOP_MEDICARE_EVENT_CODE,
    RISKPOP_MEDICAID_AID_CATEGORY,MEMBER_NO,MEDICARE_NO,MEDICAID_NO,LASTNAME,MIDINITIAL,FIRSTNAME,YMDBIRTH,
    a.SEX,CLASS,CL_DESC,S_LASTNAME,S_MIDINITIAL,S_FIRSTNAME,S_DOB,S_SEX,BENFIT_PKG,BEN_PKG_DESC,CLASS_ID,PLAN_ID,
    YMDEFF_BP,YMDEND,REASON,PRIME_SECOND,PHP_DUAL,S_ADDRESS1,S_ADDRESS2,S_ADDRESS3,S_CITY,S_STATE,S_ZIP,S_COUNTRY,
    S_PHONE,M_ADDRESS1,M_ADDRESS2,M_ADDRESS3,M_CITY,M_STATE,M_ZIP,M_COUNTRY,M_PHONE,DIV_NAME,PROV_NO,IRS_NO,
    P_LASTNAME,P_FIRSTNAME,P_MIDINITIAL,YMDEFF_PCP,ALT_KEY,ALT_CARRIER_NO,ALT_CARRIER_FUL,ALT_YMDEFF,ALT_YMDEND,
    BENFIT_PKG_EFF,BENFIT_PKG_TERM,a.MEME_CK,
    b.HIOS_NUMBER,
    null as PREMIUM_PAID_DATE,
    null as PREMIUM_PAID_END_DATE,
    b.APTC,
    null as 'GracePeriodIndicatorStartDate',
    null as'GracePeriodIndicatorEndDate',
    null as'ExchangePlanType',
    case when MEPE.CSCS_ID = 'MD11' AND grgr.GRGR_ID IN('100100','100598')
    THEN 'Y'
    ELSE 'N' end as DualCoverageIndicator
    from Extract_602_603_PBH_Extract_Main a
    left join Extract_602_603_PBH_Extract_HRI b
    on LEFT(a.MEMBER_NO,7) = b.SBSB_ID
    join FacetsReport.dbo.CMC_MEPE_PRCS_ELIG MEPE
    ON a.CLASS_ID= MEPE.CSCS_ID
    Join FacetsReport.dbo.CMC_GRGR_GROUP grgr
    ON MEPE.GRGR_CK= grgr.GRGR_CK

    >on LEFT(a.MEMBER_NO,7)
    =b.SBSB_ID
    This is not a good JOIN. It is not SARGable:
    http://www.sqlusa.com/bestpractices/sargable/
    Can you post table/index DDL? Thanks.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • XP_DELETE_FILE NOT WORKING IN SQL SERVER 2005 SP2

    Hi All,
    I have one job in sql 2005 sp2 that deletes backup older than one week.It is not working.I have checked service account permissions on backup folder and all required permissions and authentications are in place.Please let me know how to troubleshoot the
    same.
    Regards
    Rahul 

    Check the following:
    http://stackoverflow.com/questions/212603/sql-server-xp-delete-file-not-deleting-files
    QUOTE: "Note that xp_delete_file is broken in SP2 and won't work on report files;"
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Isnull is not working in sql server

    select ISNULL(price,0) price  from sales
    in some rows null is not replacing with 0

    Run:
    SELECT price, new_price=ISNULL(price,0).....
    Post results.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • How to create a dynamic multi-line function in SQL Server

    I am attempting to create a Multi-Line Function in SQL Server that accepts a dynamic WHERE clause as a parameter. I need this so that the function can be as versatile as possible for the filter that needs to be applied. I am unfortunately getting an error
    upon creation of the function.  I don't know how to solve the problem. Can someone advise me?
    SQL:
    SET
    ANSI_NULLSON
    GO
    SET
    QUOTED_IDENTIFIERON
    GO
    -- =============================================
    -- Author:
    -- Create date: 2/3/2014
    -- Description: This multiline function will accept a generic WHERE Clause and apply it to the query for return.
    -- =============================================
    CREATE
    FUNCTIONTESTMULTILINEFUNCTION
    @WHEREvarchar(1024)
    ,@CHANGEDDATEasdatetime
    RETURNS
    @TESTTABLE
    TABLE
    IDint
    ,REVint
    AS
    BEGIN
    Declare@SQLSTRINGvarchar(4096)
    SET@SQLSTRING=''
    SET@SQLSTRING=@SQLSTRING+'SELECT
    REVS.ID, REVS.Revision
    FROM
    Select distinct result.ID, Max(Rev) as ''''Revision''''
    FROM
    Select * from dbo.BugsAll
    where
    [Changed Date] < @CHANGEDDATE
    ) result
    GROUP BY result.ID
    ) REVS
    join dbo.BugsAll BA on (BA.ID=REVS.ID AND BA.REV=REVS.revision)'
    IF
    (@WHEREisnotnullOR@WHERE<>'')
    BEGIN
    SET@SQLSTRING=@SQLSTRING+'
    WHERE '+@WHERE;
    END
    INSERT@TESTTABLE
    EXEC
    (@SQLSTRING)
    RETURN
    END
    GO
    ERROR:
    Msg 443, Level 16, State 14, Procedure TESTMULTILINEFUNCTION, Line 44
    Invalid use of a side-effecting operator 'INSERT EXEC' within a function.
    Senior Test Lead -- Microsoft

    >> Unfortunately I really need to form a dynamic query in a table valued function on the SQL SERVER. I have another tabled valued function that needs something returned as a table in order to further join the data. I am not allowed to use Stored
    Procedures in that function. <<
    You do know that real SQL programmers hate the proprietary nightmare of tabled valued functions?  This is how you procedural programmers avoid learning set-oriented declarative and functional programming. 
    Your mindset wants to write to a scratch tape or disk file (aka “tabled valued function result table”) just like you did BASIC, FORTRAN or COBOL. QL programmers do not have to materialize their data. We can use VIEW or a drive table as well as a base table. 
    >> Plus, there are occasions where I don't want to pass in a field [sic: columns are not fields] parameter or need to change a parameter list such that I don't wish the table function to filter by a particular field [sic] or other setting. <<
    What you want is a magical “Automobiles, Squids and Lady Gaga” function. An SQL programmer might write a complex VIEW then do simpler SELECTs off it. 
    >> My application pushes the WHERE clause from EXCEL to SQL to do the hard work as EXCEL is not the application in which I want to process the SQL statement and pass it via ODBC. I cannot run macros in Excel on the web.<< 
    This is a crazy language system. Usually we fetch data in SQL and then pass it to a math package, report writer, etc. We never keep logic (aka WHERE clauses) outside the database. 
    >> I am bummed about the fact that this feature doesn't work. It will up my server management costs to maintain unique tabular based functions based on WHERE clause query <<
    So stop writing those “tabular based functions”, change your mindset and start learning SQL and do it right. 
    --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

  • Creation of Vendor in MDM  using Guided Procedure ...SDA not found

    Hi All, We are trying to create Master data Using Guided Procedure. After deploying MDM components on Portal we are able to see the standard iViews provided by SAP on Portal. We are using the following PDF to create the scenario. https://www.sdn.sap.

  • Where to buy a simcard to use my iPad in France?

    In the UK I can go to an apple store and purchase a SIMCARD for my iPad that allows so much data.  I would like to do the same in France.  Is that possible either at an Apple store or elsewhere?

  • Photocasting Smart Albums?

    I'm having some problems with photocasting. I can share a regular album of images, but for some reason a smart album won't work. I get the photocast icon for the smart album, and when I click it, I get the dialogue box with all the usual photocast op

  • Install problem - CF10

    I had CF10 trial version installed on a Windows 2008 Server R2.  Then Administrator stopped accepting my password.  So I ran the password reset script and restarted the service.  That didn't fix it.  So I uninstalled and when I tried to reinstall, th

  • Unable to invoke Sequence in the test package management

    Hi Experts, Today when i am working on creating test packages suddenly after selecting the node i am unable to do Sequence for the test package i tired by clciking the sequence buttton and also i tried from menu goto-->sequence. new window is not ope