TSQL – Getting every day of the Current Month

This came handy, when i wanted to get all dates of the current month when joining with mutiple tables… and not all the tables  had all dates of the month

;WITH
   CTE0 AS(SELECT 1 AS c UNION ALL SELECT 1),
    CTE1 AS(SELECT 1 AS c FROM CTE0 AS A, CTE0 AS B),
CTE2 AS(SELECT 1 AS c FROM CTE1 AS A, CTE1 AS B),
CTE3 AS(SELECT 1 AS c FROM CTE2 AS A, CTE2 AS B),
  SeqNumbers AS(SELECT ROW_NUMBER() OVER(ORDER BY c) AS SeqNumber FROM CTE3)

SELECT SeqNumber,CONVERT(VARCHAR(12),(GETDATE()-(DAY(GETDATE())-SeqNumber)),101) AS ReportingDate
FROM
    SeqNumbers
WHERE SeqNumber <=    DAY(GETDATE())

Searching through Stored procedure code using TSQL script

Even if you have a refactoring tool, sometimes i wonder what are all the storedprocedures that uses this table that starts with ‘products_’  or ‘system_’… or all the tables that have a column name ‘status_id’….

so here is the script that scans all the stored procedure code, and check if the table name is found

Note  —this will also return if the table name is in the comment too.. so the logic is, even if you want to search any text (comment) in a stored procedure

 

 

  1. ———————————————————————————————–
  2. – Parameters
  3. ———————————————————————————————–

  • DECLARE @tableNameLike VARCHAR(100), @columnNameLike VARCHAR(100)
  • – Filter only stored procedures that uses that table(s) and (optionaly) if it has a column
  • SET @tableNameLike = ‘enterYourTableName%’ — If you have organized all your tables with
  • — standard prefix, will be useful to filter
  • SET @columnNameLike = ‘enterYourColumnName%’ — Only if the table has this column
  • ———————————————————————————————–
  • – Local Variables
  • ———————————————————————————————–
  • DECLARE @spname VARCHAR(100),@TABLEname VARCHAR(100)
  • DECLARE @spnames TABLE(spname VARCHAR(100))
  • DECLARE @EXISTS INT
  • DECLARE @sp_start INT, @sp_END INT ,@t_start INT , @t_END INT,@sp_INdex INT , @t_INdex INT
  • ———————————————————————————————–
  • – DROP before Creating Temporary Tables
  • ———————————————————————————————–
  • IF EXISTS (
  • SELECT * FROM tempdb.dbo.sysobjects o
  • WHERE o.xtype IN (‘U’)
  • AND o.id = object_id(N‘tempdb..#spnames’)
  • )
  • DROP TABLE #spnames
  • IF EXISTS (
  • SELECT * FROM tempdb.dbo.sysobjects o
  • WHERE o.xtype IN (‘U’)
  • AND o.id = object_id(N‘tempdb..#TABLEnames’)
  • )
  • DROP TABLE #TABLEnames
  • – Get all the Stored procedure names
  • SELECT row_number() OVER(ORDER BY name) AS rownum,name
  • INTO #spnames
  • FROM sys.objects
  • WHERE type = ‘P’
  • – Get all the table names that passes the filter parameter
  • SELECT row_number() OVER(ORDER BY name) AS rownum,name
  • INTO #TABLEnames
  • FROM
  • sysobjects T
  • JOIN
  • INformation_schema.columns C
  • on
  • C.TABLE_NAME = T.name
  • WHERE T.name like @tableNameLike AND T.xtype = ‘U’
  • AND C.column_name like @columnNameLike
  • – SELECT * FROM #spnames
  • – SELECT * FROM #TABLEnames
  • ———————————————————————————————–
  • – Get and Set Loop Index
  • ———————————————————————————————–
  • SELECT @sp_start = 1,@sp_END = max(rownum)+1
  • FROM #spnames
  • SELECT @t_start =1,@t_END = max(rownum)+1 FROM #TABLEnames
  • – SELECT @sp_Start,@sp_END,@t_start,@t_END
  • ———————————————————————————————–
  • – Loop through each stored procedure name
  • ———————————————————————————————–
  • while @sp_start < @sp_END
  • BEGIN
  • – Get the stored procedure name
  • SELECT @spname = [name]
  • FROM
  • #spnames
  • WHERE rownum = @sp_start
  • – Loop through each tablename to check if it is used in the stored procedure code
  • while @t_start < @t_END
  • BEGIN
  • – Get the table name
  • SELECT @TABLEname = [name]
  • FROM
  • #TABLEnames
  • WHERE
  • rownum = @t_start
  • – Check if the table name exists in the stored procedure code
  • – I am using the SUM(CHARINDEX(xxx)) since the stored procedure code may span
  • – multiple rows
  • SELECT @EXISTS = SUM(CHARINDEX(@TABLEname,[text]))
  • FROM syscomments
  • WHERE id = object_id(@spname)
  • – If it is greater than zero then it is used in the stored procedure code
  • IF @EXISTS > 0
  • BEGIN
  • INSERT INTO @spnames
  • SELECT @spname
  • END
  • SET @t_start = @t_start+1 – Increment the table index
  • END
  • SET @sp_start = @sp_start+1 – Increment the storedprocedure index
  • SET @t_start = 1 – Reset the table index
  • END
  • ———————————————————————————————–
  • – To list all the spnames (remember there will be duplicates)
  • ———————————————————————————————–
  • SELECT DISTINCT * FROM @spnames
  • ———————————————————————————————–
  • – Drop the temporary tables
  • ———————————————————————————————–
  • IF EXISTS (
  • SELECT * FROM tempdb.dbo.sysobjects o
  • WHERE o.xtype IN (‘U’)
  • AND o.id = object_id(N‘tempdb..#spnames’)
  • )
  • DROP TABLE #spnames
  • IF EXISTS (
  • SELECT * FROM tempdb.dbo.sysobjects o
  • WHERE o.xtype IN (‘U’)
  • AND o.id = object_id(N‘tempdb..#TABLEnames’)
  • )
  • DROP TABLE #TABLEnames
  • ———————————————————————————————–
  • – END
  • ———————————————————————————————–
  • TSQL String Range Comparison with wildcard

    A simple note, and couldn’t find straight answer when i googled!!. so here it is..

    This is to get result from a table when filtering in string ranges that will have a wild card for ex: ‘*’

    declare @sv varchar(17),@ev varchar(17)
    declare @sindex int, @eindex int

    set @sv = ‘ABCDE11A09′
    set @ev = ‘ABCDE11A79′

    – Check the * pos if exists,if doesn’t exists return the len +1 , assuming the * at the last
    select @sindex = case when charindex(‘*’,@sv)> 0 then charindex(‘*’,@sv) else len(@sv)+1 end
    select @eindex = case when charindex(‘*’,@ev)> 0 then charindex(‘*’,@ev) else len(@ev)+1 end

    – remove the * from the range strings
    select @sv = case when charindex(‘*’,@sv)> 0 then substring(@sv,0,@sindex) else @sv  end
    select @ev = case when charindex(‘*’,@ev)> 0 then substring(@ev,0,@eindex) else @ev  end

    select @sindex,@eindex,@sv,@ev
    select mycolumn,substring(VIN,0,@sindex), substring(VIN,0,@eindex) from mytable
    where
        substring(mycolumn,0,@sindex) >= @sv AND
        substring(mycolumn,0,@eindex) <= @ev
    ORDER BY mycolumn

    IceRocket Tags: ,,

    Installing SQL Server 2008 Express with Advanced Services

    My First Impression

    Even if you don’t upgrade your older SQL database (2000 or 2005) to SQL Server 2008 Express, I see lot of benefits using the new SQL Management Studio that comes part of the SQL Server 2008 Express. The New Management is free and backwards compatible with older SQL Servers.

    The Advanced Services also includes the Reporting Services and Visual Studio (SQL Server Business Intelligence Studio) for developing reports.

    image

    Code Completion

    This is very good compare to nothing, but I still feel it could have been better, may be the basic feature limitation.. the code completion appears only on the TSQL Statements, I mean it could be nice if I type SET and shows the possible SET options like NOCOUNT ON/OFF

    image

     

     

     

     

     

     

     

     

     

     

     

     

     

    image

    image

    DTS

    DTS is back and it is good for simple export/import, but unfortunately, we can’t save the DTS package.

    image

    Simple SCRUM with SharePoint 2007 and Outlook 2007 in Agile Product Development

    Being in the software development for over 10 years, started working in a software service industry in the first half of my career then moving to a product development, I find myself it is a cultural change or should I say I reinvented myself many times, getting a better process or discipline on delivering Quality Software on time and budget.

    I do think every product development has to be Agile, wether you are  part of the product management or product development. You would agree, when you don’t know who is your next customer or you don’t know your next customer want. There is so much goes in a product development at least for simplicity we can say product evolves with (a) tracking the market/customer needs and (b) following Technology evolution

    Understanding the nature of the business, and understanding the engineers and managers who involve in getting the product out, and the emotions that goes along during the changes happens that are unplanned and You as a product owner helping everyone to cope up to adopt the changes. it is a challenge and it doesn’t happen easily if you don’t have the right team. The Right team is not just a well qualified and skilled people, but it needs more than that, you will also agree you need a team full of self-responsible individuals  who respects professional ethics and trust between the team members.

    Having tried a simple excel sheet to MS Project and writing several documents, I always wanted to keep things simple and by simple I mean, the process should evolve to meet our needs and not the other way around.

    I always wanted to just use one single tool to communicate and coordinate and collaborate with all my team members, including product management, support and development. Common to all of us here is Outlook 2007, so I could not think of better tool to implement SCRUM and make it more effective, I wanted the information to reach to the team members instead they have to go for it to know what is changed or make an update.

    Also I instituted the daily 5 minutes Stand up meeting – each will get about 5 minutes to state what they are going to work on today and if they need help from anyone and a weekly meeting to do recap of how it went and the plan for the next week. This really brings everyone a greater visibility of the overall picture and also makes everyone feel they are part of a team.

    How it Works

    This is a solution, you can think of it like, using as it is,  SharePoint 2007 as a back end and Outlook 2007 as a front end for all your cross functional team (sales/marketing/development/support) without writing any custom code.

    As I started working SharePoint Server to integrate the reports Reporting Services, I started to explore and discovered the simple project tasks web part, and the “Connect to the Outlook” (you will need outlook 2007),  RSS Feed and Alert Me.

    The important thing here to note is this integration with Outlook and ability to add RSS Feeds in Outlook and Alert Me feature.

    By setting up the Bucket lists as a RSS Feed in your outlook, so any time, when a new item is added in the bucket lists, you will get a notification and for example, the Sales or Marketing or anyone who gets an idea or finds a need for your product, they can simply post  a new item to the bucket lists using their Outlook, without having to open the browser or searching for a link where to post. As soon as you (Product Owner) get a notification by setting the “Alert Me”, then you can analyze add minimum/required information. 

    When you assemble a Sprint/Project Tasks, developers will get an email notification as and when they get assigned to a task. And  the developers on the other hand can configure the Sprint/Project Tasks in their Outlook using “Connect to Outlook”, so they don’t have to open the browser again to update the status or get visibility of the overall status

     

    PROJECT Backlog/Bucket Lists

    I customized the SharePoint List as a Bucket Lists as a template, so I can capture all the necessary details, as you can see below:

    bucketlists

     

    Project Tasks as SPRINT

    This Projects Tasks Web Part, I use it as a sprint, will show only the active tasks that are being worked

    Project Tasks Web Part in SharePoint 2007

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    projectsTasksGanttView

     

    Connect to Outlook, View RSS Feed and Alert Me

    outllokconnectorandRSS

    IceRocket Tags: ,,,

    SQL Express 2005 – A Basic ETL Trick

    For anyone using the SQL Express 2005, and going over or got over the frustration of not having the DTS… and more over not  able to use SSIS as some type of runtime that you distribute with your packaged software application…

    Well, i thought i would share what i did, it is not rocket science, but works to extract the data without writing another module to maintain, rather using only command line or a batch file using sqlcmd.

    If you haven’t explored sqlcmd, please do so, just go to the command line, and type sqlcmd/?, you can all kinds of options, and particularly we can look at the options that will let you execute the sql directly or better, you can pass a file with set of sql or stored procedure to execute.

    I could have done this creating a stored procedure, but i didn’t want to modify the 3rd party application’s database, so i wrote a  getxmldata.sql  which outputs a results in xml (you can find everywhere how to output data in xml format using tsql)

    then i wrote a batch file getxmldata.bat

    sqlcmd -Slocalhost\MyDatabaseInstanceName -E -d MyDatabaseName -i getxmldata.sql -o output.xml

    Something more to explore..

    You can pass parameters to the your batch file and pass it to your sql file .. to make it more dynamic..

    and if you want to schedule this bat file to run, frequently say every one hour or every 15 minutes..  you can use the windows scheduler to run this batch file..

    you know where to find the windows tasks scheduler? it has a nice wizard to do what you want to do… if you can’t find it.. ask me…

     

    SaaS as a Service – OEM / VAR/ branding ? Hierarchical Multi-tenant design

    This may not be a new concept or a new idea, but many of use wouldn’t have noticed.. or at least when I try to see in internet search, I didn’t read much, so I thought I will blog what I know.

    What is this – SaaS as a Service or why?

    Imagine, being a SaaS company, where does a situation comes you will need someone to resell your product in SaaS model with a different brand or same, or with different features or capabilities or may be more localized. So this is more of a situation, as it appears the value added resellers are the service providers, who have been using your product to manage their clients and services, and now when you want to move from On-premise to a SaaS model, you still want to carry over your client base of value added resellers(VAR).

    Another situation, being a ISV, you may not want to develop all the necessary building blocks by yourself, but you may want to include some other services like Licensing, billing, integration, maps, storage, computing services from another vendor in your SaaS delivery but at the end it is delivered to the end user as one solution. This is typically called mash-ups, but I am trying to extract the scenario where ISV needs to use the mash-ups, and those services are available to the ISVs enabling the customization and present themselves as a OEM or VAR Channel partner.

    So what is this Hierarchical Multi-tenant design?

    Well I can read lot about the SaaS and how-to , all over the web. So I don’t need to explain here again in detail. So if we all understand, (SaaS) Multi-tenant is all about every data we store in the database, can now identify which tenant it belongs to, instead of maintaining one database per tenant rather share the database server, computing power and the application code for all the tenants. And if you are in a early stage development and if you are considering the multi-tenant database, you will need to consider including another element so that your data can now identify the hierarchy of your accounts .

    Let’s say the company “SAASIFY”, wants to sell their services all over the world, and instead of selling directly, it wants to sell through OEM/VAR Channels. So their product is delivered through SaaS model all their customers (VAR channels) or OEM.

    SAASIFY can focus on developing the software, hosting and RASP (Reliability, Availability, Scalability, Performance), may not sell the services directly, but may generate collaborative marketing effort for all the customers. Each of those partners again, they can just focus on selling the services not to worry about maintaining or administering the software. When they login, they can see all their customers, and allow each of their customers to login in to the same system to manage/administer themselves.

     

     

     

    SaaS in the Clouds for a Newbie

    Software as a Service:

    Software … if you install Microsoft word and create documents.. and then uninstall.. the documents stays there on your computer.. the software is the “Microsoft Word” not the data it creates.

    Now if you want to use this “Microsoft Word” Software, from many computers, anywhere in the world,  and access to the documents you create…  you can notice two things:

    1.  You click an Icon, you always have a latest “Microsoft Word”, it is always available to you no matter which computer you use (assume you do login and pay subscription fees) without installing any software in any of the computers you use.

    2. When you start using the software, it knows what are your data, it gives access to only your files (data).

     Both Software and Data is available somewhere in the Internet – Cloud,  to run the Software in the Cloud,  imagine it is not just going to be one software, and you are not the only person going to use the software, imagine the computer with  thousands of computing power.

     

    Cloud Computing:

    For all software developing companies, if they want to provide their software as a service,  they need to host their software somewhere in the cloud and provide storage to store and access the user’s data.  Also they will have to store all the user’s data in the same place, but the data identifies itself whom it belongs to (Multi-tenancy) think of like a apartment number, if you are living in apartments complex sharing the same address.

     

    If I own a software company, I want to worry about the software and value I deliver to my customers, and not to worry about the where to host or the infrastructure, billing, licensing, storage, connectivity…  and also my software may use some other software available in the internet as a service, say I want to show stock prices in my software or show Maps from google for the addresses

     

    So I can go host my server in Amazon EC2, use storage as a service , database as a service, use Opsource’s bus or integrating enterprise applications  service or use google’s map service… now delivering my application in the clouds combined with many other services – Cloud computing

    In simple terms, if you can imagine the benefits now..  when i release a software, i can make it available to all my customers, and create more opportunities to generate more revenue..  and for the customers, no hassle of installing, maintaining a software and pay only for what they use for.

     

     

     

    Trust your Instincts

    Sometimes it may be just as which turn to take, when we are driving without a map.. or  making decision which direction to take in product roadmap to do in next 2 years..  there are many times, i wonder about my previous decisions.. did i trust my instincts.. or did i just went on with what others said…

    Trusting our instinct is not about whether we are making a right decision or not.. I realized it is about how much confident i am…

    I remember when I finished my first consulting project 2 months ahead of given time, in 2000. and it was a dot.com crash time.. and it  took my employer 3 months to find a next project.. well.. to keep up with technology and anyway i was getting paid to be at home, moreover it was winter in Boston.. so i registered a website.. www.livingpartners.com… and the concept was to manage the accounting of houshold shared by those living Singles…  being myself.. taking notes in a paper and excel sheets.. who spent what and tallying every now and then…  who owes whom and how much… and so i did it.. i had a website.. a group can create an account.. and create members of the group..each can post what they spent.. i had regular categories/expense types.. or add your own types..and select who shares how much.. all click and save.. and anytime you can request to show a report of how much you spent.. and tallys with others spent on you.. and gives simple sheet of who owes how much to whom….      my roommates used to make fun of me…. as the website name livingpartners meant for pets etc… or take your wild imagination…

    Later when i got busy with other projects/clients.. and i discontinued the livingpartners.com… Now may be this is not a great science I invented, but I came to know last year.. there is a  http://www.ioweyou.co.uk/ .. . by any means.. i don’t mean to say they copied my idea … i am glad someone else also thought of the same idea.. and built a business around it…

    I always thought this is a neat idea.. and i always wanted to make it such a way.. to design this application to make this data available for more than just for sharing expenses.. and wanted to make it available for general websites like roommates.. kinda idea of what is social networking today… 

    Even in our every day, at work , at home… we are very creative and inventing as little as solving a simple problem.. when we do.. we don’t know how little it is or how big it is.. until we take the courage to trust our instincts…

     

    Backup/Restore – Export / Import data using SQL Scripts

    The Surveillance monitoring and management product (ASP.NET/SQL Express), a browser based application, we are releasing as a product (on-premise solution) and the same is also available hosted as a SaaS Application.

    So for both scenarios, i wanted to develop a feature to allow customers to backup and restore their data and the same i wanted to use in software install kit, when we do software upgrade.

    There are many solutions i read in the internet, which pretty much goes over, hosting the web application and do the backup/restore using backend database tools, or use bulk copy/insert.  Or there are samples of writing code that will very specific to my application. 

    The code I wrote for this application, I feel very generic and could be used for any similar size (data) application. Ofcourse there is lot of room for improvement.

    The concept:

    We have 2 stored procedures, ExportDBAsXML and ImportDBFromXML, the ExportDBAsXML exports all the data in the database to a xml string (how big size this can handle.. i have to test.. but so far it is working out good for me), and ImportDBFromXML imports thata data from the xml string (exported from the ExportDBAsXML) to the database.

    Two Sql Scripts used during the installation for software upgrade, the backup.sql and restore.sql uses the ExportDBasXML and ImportDBFromXML respectively.

    The Code is my documentation.. so mail me.. if its not clear enough…

     

    ——————————————————————————–

    Backup.sql

    ———————————————————————————

    USE [YOUR DATABASE]
    DECLARE @return_value int,
      @outputXML nvarchar(max)

    – Get all data from all the tables in the database

    EXEC @return_value = [dbo].[sp_ExportDBAsXML]
      @outputXML = @outputXML OUTPUT

    – check if the temporary table exists, and if exists drop it

    If Object_Id(‘t_backupData’) is Not Null
     DROP TABLE t_backupData

    – Create a temporary table  and insert the data exported from the database as xml
     
    CREATE TABLE t_backupData(oldData nvarchar(max))
    INSERT t_backupData VALUES (@outputXML )

    – Drop temporary table created by ExportDBAsXML (second check — not necessary but as safety check)
    – Delete any old t_userTables temporary table
    IF EXISTS( SELECT name FROM sysobjects where xtype = ‘U’ and name like ‘t_userTables’)
       DROP TABLE t_userTables

     

    ——————————————————————————–

    Restore.sql

    ———————————————————————————

    USE [YOUR DATABASE]

    DECLARE @return_value int,
      @returnValue int,
      @returnMessage nvarchar(1000)

    DECLARE @oldData nvarchar(MAX)

    – Read the data from the temporary table

    SELECT @oldData = oldData FROM t_backupData

    EXEC @return_value = [dbo].[sp_ImportDBFromXML]
      @outputXML = @oldData,
      @returnValue = @returnValue OUTPUT,
      @returnMessage = @returnMessage OUTPUT

    DROP TABLE t_backupData

    ——————————————————————————–

    ExportDBAsXML

    ———————————————————————————

     CREATEPROCEDURE [dbo].[sp_ExportDBAsXML]
      (@outputXML nvarchar(max) OUT)

    AS
    BEGIN
     SET NOCOUNT ON;

      DECLARE @userTableName nvarchar(50)

      IF EXISTS( SELECT name FROM sysobjects where xtype = ‘U’ and name like ‘t_userTables’)
       DROP TABLE t_userTables

      SELECT name INTO t_userTables
      FROM sysobjects where xtype = ‘U’ and name <> ‘t_userTables’ and upper(name) like ‘tableStartTag%’

    — tableStartTag — replace this with your table name standards.. also helps to filter the tables you want to do the backup.

      If Object_Id(‘tempdb..#xmltable’) is Not Null
      DROP TABLE #xmltable

      CREATE TABLE #xmltable (string XML)

      DECLARE @tableCount int

      SELECT @tableCount = count(*) FROM t_userTables

      WHILE(@tableCount > 0)
      BEGIN
       SELECT TOP 1 @userTableName = name FROM t_userTables

       INSERT #xmltable EXEC (‘SELECT * from ‘ + @userTableName + ‘ FOR XML AUTO, TYPE’)

       DELETE t_userTables WHERE name = @userTableName
       SELECT @tableCount = count(*) FROM t_userTables

      END
      
      SET @outputXML = ”

      SELECT  @outputXML = CONVERT(nvarchar(max),string)+  @outputXML FROM #xmltable WHERE string is not NULL
      SET  @outputXML =  ‘<YOUR_XML_ROOT_TAG>’ + @outputXML + ‘</YOUR_XML_ROOT_TAG>’

      DROP TABLE #xmltable
      DROP TABLE t_userTables
      

    END

    ——————————————————————————–

    ImportDBFromXML

    – there are few extra checkings for Data Version, you can use it or chenge it as necessary

    – YOUR_Application table maintains the information about the applicaton information such as version number, date etc.

    ———————————————————————————

    Create PROCEDURE [dbo].[sp_ImportDBFromXML]
      (@outputXML nvarchar(max) ,
       @returnValue int OUT,
       @returnMessage nvarchar(1000) OUT
      )

    AS
    BEGIN
     SET NOCOUNT ON;
      DECLARE @userTableName nvarchar(50)
      DECLARE @sql nvarchar(max)


      SET @returnValue = -1
      SET @returnMessage = ‘Failed to Import Data’;

      DECLARE @DATA_Version nvarchar(50)
      DECLARE @CURRENT_Version nvarchar(50)

      SELECT @CURRENT_Version  = ISNULL(APP_Version,’0.0.0.0000′) FROM YOUR_Application 
      – Delete any old t_userTables temporary table
      IF EXISTS( SELECT name FROM sysobjects where xtype = ‘U’ and name like ‘t_userTables’)
       DROP TABLE t_userTables

      – Read XML data to get version and table information 
      DECLARE @idoc int
      EXEC sp_xml_preparedocument @idoc OUTPUT, @outputXML

     
      – Get the tables from the XML Data  
      SELECT
       DISTINCT localname INTO t_userTables
      FROM
       OPENXML(@idoc, ‘/YOUR_XML_ROOT_TAG/’,1) WHERE parentid = 0 AND upper(localname) like ”tableStartTag%’ AND upper(localname) <> ‘YOUR_APPLICATION’
      
      IF NOT EXISTS(SELECT APP_Version FROM OPENXML(@idoc, ‘/YOUR_XML_ROOT_TAG/YOUR_Application’,1) WITH YOUR_Application)
       SET @DATA_Version = ‘0.0.0.0000′
      ELSE
       SELECT @DATA_Version = ISNULL(APP_Version,’0.0.0.0000′) FROM OPENXML(@idoc, ‘/YOUR_XML_ROOT_TAG/YOUR_Application’,1) WITH YOUR_Application 

     

      EXEC sp_xml_removedocument @idoc

    – to prevent forward compatiblity – who know what changes in the future
      IF  @DATA_Version > @CURRENT_Version
      BEGIN
       SET @returnValue = -1;
       SET @returnMessage = ‘Imported Data Version : ‘ + @DATA_Version + ‘ not  supported in this Version : ‘ + @CURRENT_Version;
       RETURN @returnValue;
      END
     
      
      DECLARE @table_Exists int
      SELECT @table_Exists = COUNT(*) FROM t_userTables

      WHILE(@table_Exists > 0)
      BEGIN

       SELECT TOP 1 @userTableName = localname FROM t_userTables

       IF @userTableName = ‘YOUR_Application’
        GOTO CONITNUE_LABEL

       IF @userTableName = ‘t_userTables’
        GOTO CONITNUE_LABEL

     

    – just a sample of special table, not necessary if you don;t have any

    – special table check

     

       IF @userTableName = ‘Your_specialtable’ AND @DATA_Version < ‘YY.YY.YY.YYYY’
        BEGIN
         – Special check if the table name is Your_specialtable and data version is less than YY.0
         SET @sql = ‘DELETE FROM Your_specialtable’
         EXEC (@sql)
         SET @sql = ‘DECLARE @idoc int ; EXEC sp_xml_preparedocument @idoc OUTPUT, ”’ + @outputXML + ”’ ;’ +
            ’INSERT INTO Your_specialtable’ +
           ’ SELECT * ‘ +
           ’ FROM OPENXML(@idoc, ”/YOUR_XML_ROOT_TAG/’ + @userTableName + ”’,1) WITH Your_specialtable; ‘ +
           ’EXEC sp_xml_removedocument @idoc ; ‘
         EXEC (@sql)
         
        END
       ELSE
        BEGIN  
         SET @sql = ‘DELETE FROM ‘ + @userTableName
         EXEC (@sql)
         SET @sql = ‘DECLARE @idoc int ; EXEC sp_xml_preparedocument @idoc OUTPUT, ”’ + @outputXML + ”’ ;’ +
            ’INSERT INTO ‘ + @userTableName +
           ’ SELECT * ‘ +
           ’ FROM OPENXML(@idoc, ”/YOUR_XML_ROOT_TAG/’ + @userTableName + ”’,1) WITH ‘ +
           @userTableName + ‘;’ +
           ’EXEC sp_xml_removedocument @idoc ; ‘
         EXEC (@sql )
         
     – Update Application ID if the data imported is older than XX.XX.XX.XXXX
          IF @DATA_Version < ‘XX.XX.XX.XXXX’
          BEGIN     
          – Again this is if only required, assuming  each table has someway to uniquely identify its application ID 
           IF EXISTS(SELECT name FROM syscolumns where id = object_id(@userTableName) and name like ‘ApplicationId’)
           BEGIN

     

            set @sql = ‘update ‘ + @userTableName + ‘ set applicationid = dbo.getapplicationGUID(””)  WHERE applicationid  IS NULL’;
            EXEC (@sql)

           END       
          END
         
        END

       CONITNUE_LABEL:
        – Remove the table from the temporary Table
        DELETE t_userTables WHERE localname = @userTableName
        SELECT @table_Exists = COUNT(*) FROM t_userTables

     
      END

      DROP TABLE t_userTables
      SET @returnValue = 0
      SET @returnMessage = ‘Sucessfully Imported Data’;

      

    – execute your stored procedure  to setup default values

    – I maintained a seperate stored procedure to insert/update all the default values (applicatin meta data) and also re-wiring  the administrator Access rights.
      EXEC dbo.sp_SetupDefaultValues”
      
      return @returnValue 

    END

     

     

     

    ———————————————————————————