How to maintain previous and record count in audit table in SQL Server 2008 r2?

Hi Experts ,
 Situation :
in our database we are having few of stored procedures which will drop and recreates the tables and it is scheduled on weekly basis. when this job will run all the stored procedures will drop all the tables and recreate. Now we need to create one table which
will maintain history of the records.
my table structure is listed below
TableName CurrentReocrdCount CurrentExecutionDate PreviousReordCount PreviousExurtiondate
TEST         1000                   2014-03-30            NULL        NULL
Test         1500                   2014-04-10            1000      2014-03-30
Test         2000                   2014-04-11            1500      2014-04-10 
How do i achive this . 
franklinsentil

You need to create audit tables for these. The table will be populated by COUNT value inside stored procedure. Each time it clears the main table and fills new data and also logs count details to audit tables. You can use COUNT(*)  to get count value
and GETDATE function to get current execution value.
So proc will look like
CREATE PROC procname
@param....
AS
--step to drop existing table
IF OBJECT_ID('tablename') IS NOT NULL
DROP TABLE <table name>
--step to fill new table
SELECT ...
INTO TableName
FROM
--Audit table fill step
INSERT AuditTable (TableName,CurrentRecordCount,CurrentExecdate,PrevRecordCount,PrevExecDate)
SELECT TOP 1 'TableName',(SELECT COUNT(*) FROM tableName),GETDATE(),CurrentRecordCount,CurrentExecDate
FROM AuditTable
ORDER BY CurrentExecDate DESC
UNION ALL
SELECT 'TableName',(SELECT COUNT(*) FROM tableName),NULL,NULL
WHERE NOT EXISTS (SELECT 1 FROM AuditTable)
GO
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • How to extract data from multiple flat files to load into corresponding tables in SQL Server 2008 R2 ?

    Hi,
              I have to implement the following scenario in SSIS but don't know how to do since I never worked with SSIS before. Please help me.
              I have 20 different text files in a single folder and 20 different tables corresponding to each text file in SQL Server 2008 R2 Database. I need to extract the data from each text file and
    load the data into corresponding table in Sql Server Database. Please guide me in how many ways I can do this and which is the best way to implement this job.  Actually I have to automate this job. Few files are in same format(with same column names
    and datatypes) where others are not.
    1. Do I need to create 20 different projects ?
                   or
        Can I implement this in only one project by having 20 packages?
                 or
        Can I do this in one project with only one package?
    Thanks in advance.

    As I said I don't know how to use object data type, I just given a shot as below. I know the following code has errors can you please correct it for me.
    Public
    Sub Main()
    ' Add your code here 
    Dim f1
    As FileStream
    Dim s1
    As StreamReader
    Dim date1
    As
    Object
    Dim rline
    As
    String
    Dim Filelist(1)
    As
    String
    Dim FileName
    As
    String
    Dim i
    As
    Integer
    i = 1
    date1 =
    Filelist(0) =
    "XYZ"
    Filelist(1) =
    "123"
    For
    Each FileName
    In Filelist
    f1 = File.OpenRead(FileName)
    s1 = File.OpenText(FileName)
    rline = s1.ReadLine
    While
    Not rline
    Is
    Nothing
    If Left(rline, 4) =
    "DATE"
    Then
    date1 (i)= Mid(rline, 7, 8)
     i = i + 1
    Exit
    While
    End
    If
    rline = s1.ReadLine
    End
    While
    Next
    Dts.Variables(
    "date").Value = date1(1)
    Dts.Variables(
    "date1").Value = date1(2)
    Dts.TaskResult = ScriptResults.Success
    End
    Sub

  • How to hide not all but a specific database on a SQL Server 2008 R2 instance?

    Hello everyone,
          I need help from all the SQL Server database security experts out there. Any solution/help or work-around will be really appreciated. Here is the scenario; our client is using our application which is a windows forms application
    having in backend as a database under SQL Server 2008 R2 instance. We have successfully installed the SQL Server software with mixed mode authentication on client side, our application is running smoothly and everything is working fine. Our database on which
    application is running is quite intuitive, in the sense, all employees information is stored in EmployeeMaster and all departments information is stored in DepartmentMaster and so on. It consists of more than 500 such tables, stored-procedures and views. We
    have encrypted stored-procedures and views, problem is only with tables.
    We don't want table structure to be visible to anybody in SSMS (or tables must be hidden from all the users) but at the same time the tables should be accessible from the application. And we don't want to go with the option of encrypting
    the tables data and changing the names of all the tables to T001,T002..etc. as that is not feasible. And one last thing, we cannot restrict 'sa' login's password, it has to be shared with the client.
    Regards,
    Sumit R. Santani

    Also, will you please enlighten me more on what you said as "couple of choices" if I want to lock out plain users only?
    Assuming that you are selling a solution to a client, it's more an issue for your client's IT department, that do want their users to connect with Excel or SSMS.
    Anyway, I have a brief overview here:
    http://www.sommarskog.se/grantperm.html#Othermethods
    Again my question on that is how much reliable will be that license agreement?
    That depends on the lawyer you engage to write the license agreement.
    How would I come to know what they are doing with our database?
    Trust. Trust is extremely important. It is very difficult to make business if you don't trust people.
    That said, there are basically two reasons you want to hide the application from the client. One is protecting intellectual property. To this end, I know of nothing else than trust. And maybe after all, your application is not so fantastic that it is worth
    stealing anyway.
    The other reason is that you don't want the client to change it, and then open a free support case when he has messed up. To this end there are some technical approaches you can take to detect such tampering. For instance, you can sign all stored procedures
    with certificates using ADD SIGNATURE WITH SIGNED BLOB, and then ship only the public key of the certificate. This permits SQL Server to verify the signature, but the client cannot change the signature and sign it with that certificate, because the private
    key is not available to them.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to change the name of the named instance in MS sql server 2008 R2

    Hi Gurus
    I have installed a  SAP ECC 6 ehp4 on MS sql server 2008 R2 with MS windows 2008 R2 OS.  While installing sql server i have selected  named instance from  window(default instance, named instance).   and given name  QAS.
    and installed ECC6 ehp4 ABAP engine successfully. now i want to change the name of mssql server's named instance name to DEV.
    kindly let me know
    which one is the best and easy solution
    1. changing the name of named istance at database level and SAP.
    2. or uninstalling  the existing SAP, DB and start from scratch.
    if first is the best, what would be the steps
    Thanks in advance
    balaji

    Hello,
    Please check this note:
    11692 - Renaming the system ID
    regards,
    John Feely

  • How can I maintain start_time and end_time in my audit table for mydbms_job

    Hi Guys,
    Need some help on runing this job, I need to maintain start_time and end_time. However we are getting job details from the user_jobs table.
    DECLARE
    l_job BINARY_INTEGER;
    BEGIN
    DBMS_JOB.SUBMIT(l_job, '<your job code>', sysdate, 'sysdate + 1/24');
    COMMIT;
    END;
    Here I am planing to use audit log table which I have created with job_name,start time,end_time. Once I execute this job, I need to audit the job with start and end times. Is it possible.
    can any one help me on this.
    Thanks in advance!
    -KLR.

    If you switch from dbms_job to using dbms_scheduler (as recommended by oracle) then this auditing information would be delivered out of the box. For scheduler jobs there are much better dictionary information then for the older dbms_jobs solutions.
    Views like this
    select * from user_SCHEDULER_JOBS;
    select * from USER_SCHEDULER_JOB_LOG;
    select * from USER_SCHEDULER_JOB_RUN_DETAILS;

  • 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

  • How to parse XML and store the data in  tables using sql or plsql?

    I want to parse the xml
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xmlListWrapper>
        <size>2</size>
    <AppTypeID>10</AppTypeID>
    </xmlListWrapper>
    and store in a table
    |pk|apptypeid|
    1     10

    You can extract data from your XML along these lines...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select xmltype('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
      2  <xmlListWrapper>
      3    <size>2</size>
      4    <AppTypeID>10</AppTypeID>
      5    <AppTypeID>20</AppTypeID>
      6  </xmlListWrapper>') as xml from dual)
      7  --
      8  -- end of example data
      9  --
    10  select x.*
    11  from   t
    12        ,xmltable('/xmlListWrapper/AppTypeID'
    13                  passing t.xml
    14                  columns pk for ordinality
    15                         ,apptypeid number path '.'
    16*                ) x
    SQL> /
            PK  APPTYPEID
             1         10
             2         20
    SQL>
    Inserting it to a table is obviously achieved using an INSERT ... SELECT ... where the SELECT is extracting the data from the XML.

  • How to merge three columns values to single row values in sql server 2008

    Hi Frds.....
    I have three quantity in my table.
    Quantity1,quantity2,quantity3
    this three quantity have different values
    ex:
    quantity1 = 1000,quantity2=2000,quantity3=3000
    the three column combine 2 display in single row values. this values display in one by one.
    ex: quantity
         1000
         2000
         3000

    You will need to use the UNPIVOT operator:
    DECLARE @example TABLE
    Id int NOT NULL IDENTITY(1,1),
    Quantity1 int,
    Quantity2 int,
    Quantity3 int
    INSERT INTO @example VALUES (1000, 2000, 3000), (4000, 5000, 6000);
    SELECT * FROM @example;
    SELECT Id, Quantity, QuantityType
    FROM @example
    UNPIVOT
    Quantity FOR QuantityType IN (Quantity1, Quantity2, Quantity3)
    ) AS u;
    Output:
    (2 row(s) affected)
    Id Quantity1 Quantity2 Quantity3
    1 1000 2000 3000
    2 4000 5000 6000
    (2 row(s) affected)
    Id Quantity QuantityType
    1 1000 Quantity1
    1 2000 Quantity2
    1 3000 Quantity3
    2 4000 Quantity1
    2 5000 Quantity2
    2 6000 Quantity3
    (6 row(s) affected)

  • How to attach .mdf file to sql server 2008 EXPRESS

    I have .mdf files created using SQL SERVER management studio 2012 in another computer and wish to attach the same to SQL SERVER 2008 EXPRESS in another computer. How should I do so? I tried this method :How
    to: Attach a Database File to SQL Server Express but then it shows an error that the database cannot be created due to compatibility issues.
    Msg 948: The database xyz cannot be opened because it is version 706. This server supports version 655 and earlier. A downward path is not supported..
    Any help??

    I have .mdf files created using SQL SERVER management studio 2012 in another computer and wish to attach the same to SQL SERVER 2008 EXPRESS in another computer. How should I do so? I tried this method :How
    to: Attach a Database File to SQL Server Express but then it shows an error that the database cannot be created due to compatibility issues.
    Msg 948: The database xyz cannot be opened because it is version 706. This server supports version 655 and earlier. A downward path is not supported..
    Any help??
    You are trying to attach SQL Server 2012  database files to SQL Server 2008 R2 which is not allowed, you either need to upgrade your SQL Server 2008 to 2012 or alternatively you can generate all scripts from SQL Server 2012 and execute it in SQL Server
    2008 R2.
    You can refer below link to how to generate script.
    http://blog.sqlauthority.com/2012/07/18/sql-server-generate-script-for-schema-and-data-sql-in-sixty-seconds-021-video/
    Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    Praveen Dsa | MCITP - Database Administrator 2008 |
    My Blog | My Page

  • Need clear steps for doing performance tuning on SQL Server 2008 R2 (DB Engine, Reporting Services and Integration Services)

    We have to inverstigate about a reporting solution where things are getting slow (may be material, database design, network matters).
    I have red a lot in MSDN and some books about performance tuning on SQL Server 2008 R2 (or other) but frankly, I feel a little lost in all that stuff
    I'am looking for practical steps in order to do the tuning. Someone had like a recipe for that : a success story...
    My (brain storm) Methodology should follow these steps:
     Resource bottlenecks: CPU, memory, and I/O bottlenecks
     tempdb bottlenecks
     A slow-running user query : Missing indexes, statistics,...
     Use performance counters : there are many, can one give us the list of the most important
    how to do fine tuning about SQL Server configuration
    SSRS, SSIS configuration ? 
    And do the recommandations.
    Thanks
    "there is no Royal Road to Mathematics, in other words, that I have only a very small head and must live with it..."
    Edsger W. Dijkstra

    Hello,
    There is no clear defined step which can be categorized as step by step to performance tuning.Your first goal is to find out cause or drill down to factor causing slowness of SQL server it can be poorly written query ,missing indexes,outdated stats.RAM crunch
    CPU crunch so on and so forth.
    I generally refer to below doc for SQL server tuning
    http://technet.microsoft.com/en-us/library/dd672789(v=sql.100).aspx
    For SSIS tuning i refer below doc.
    http://technet.microsoft.com/library/Cc966529#ECAA
    http://msdn.microsoft.com/en-us/library/ms137622(v=sql.105).aspx
    When I face issue i generally look at wait stats ,wait stats give you idea about on what resource query was waiting.
    --By Jonathan KehayiasSELECT TOP 10
    wait_type ,
    max_wait_time_ms wait_time_ms ,
    signal_wait_time_ms ,
    wait_time_ms - signal_wait_time_ms AS resource_wait_time_ms ,
    100.0 * wait_time_ms / SUM(wait_time_ms) OVER ( )
    AS percent_total_waits ,
    100.0 * signal_wait_time_ms / SUM(signal_wait_time_ms) OVER ( )
    AS percent_total_signal_waits ,
    100.0 * ( wait_time_ms - signal_wait_time_ms )
    / SUM(wait_time_ms) OVER ( ) AS percent_total_resource_waits
    FROM sys.dm_os_wait_stats
    WHERE wait_time_ms > 0 -- remove zero wait_time
    AND wait_type NOT IN -- filter out additional irrelevant waits
    ( 'SLEEP_TASK', 'BROKER_TASK_STOP', 'BROKER_TO_FLUSH',
    'SQLTRACE_BUFFER_FLUSH','CLR_AUTO_EVENT', 'CLR_MANUAL_EVENT',
    'LAZYWRITER_SLEEP', 'SLEEP_SYSTEMTASK', 'SLEEP_BPOOL_FLUSH',
    'BROKER_EVENTHANDLER', 'XE_DISPATCHER_WAIT', 'FT_IFTSHC_MUTEX',
    'CHECKPOINT_QUEUE', 'FT_IFTS_SCHEDULER_IDLE_WAIT',
    'BROKER_TRANSMITTER', 'FT_IFTSHC_MUTEX', 'KSOURCE_WAKEUP',
    'LAZYWRITER_SLEEP', 'LOGMGR_QUEUE', 'ONDEMAND_TASK_QUEUE',
    'REQUEST_FOR_DEADLOCK_SEARCH', 'XE_TIMER_EVENT', 'BAD_PAGE_PROCESS',
    'DBMIRROR_EVENTS_QUEUE', 'BROKER_RECEIVE_WAITFOR',
    'PREEMPTIVE_OS_GETPROCADDRESS', 'PREEMPTIVE_OS_AUTHENTICATIONOPS',
    'WAITFOR', 'DISPATCHER_QUEUE_SEMAPHORE', 'XE_DISPATCHER_JOIN',
    'RESOURCE_QUEUE' )
    ORDER BY wait_time_ms DESC
    use below link to analyze wait stats
    http://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/
    HTH
    PS: for reporting services you can post in SSRS forum
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers

  • How to maintain a condition record for a output type ?

    Hi All
    How to maintain a condition record for a output type ?

    Hi,
    Goto NACE and there is a button for maintiaining the Condition Reocrds.

  • SAP BO Report Execution time and Record count

    Hi All,
    We have a requirement to set the limits on report execution time and record count centrally. Can you please help me to identify where exactly we have to define the settings in CMC for BO4.
    Thanks in advance,
    Shalini

    Hi Shalini,
    Please follow these steps, also check in for any more details if any;
    Step 1: Launch CMC
    Step 2: Select Servers
    Step 3: Select Web Intelligence processing Server, right click and Goto Properties
    Step 4: Maximum List Of Values Size (entries) default value is 50000.
    Step 5: Increase this value if your "LOVS" greater than this value.
    Step 6: Save and close.
    Step 7: Restart the server.
    Hope this helps.
    - Ram

  • How to get a total record count before grouping?

    I need to group a report on a formula that does roughly the following:
    [record count] / ( [total record count] / 20 )
    What this acheives is to label each record with a number of 1 - 20 which I want to group on. Getting this figure is the easy part, what is not working is the fact that I cannot group from a formula that is calculated after grouping. I overcame a portion of this by using "Whilereadingrecords" (rather than "count", running totals, or while printing records) to acheive a record count.
    I can't figure out how to get a total record count done before grouping. Is there a way to do this with "WhileReadingRecords"?? Is this even possible?
    Thanks
    John

    Hi John, 
    The order of how Crystal does things dictates the order of which features you can use.  Crystal has a two pass method.  In the first pass it does things like passing the query, grouping, summarizing.  In the second pass it does formulas, formatting, etc. 
    Unfortunately Crystal does the Grouping before summarizing so what you want to do can't be done in Crystal.  The best way to get around this to either create a SQL Command or view/stored procedure that will do the summarizing for you.  Then in the report you can use it. 
    Hope this helps,
    Brian

  • Get records count of all tables

    Hi ,
    I am trying to get the record count of all tables using dynamic query. I don't know how to put the value in placeholder. I tried the below code.
    SET SERVEROUTPUT ON SIZE 1000000
    DECLARE
         CURSOR table_list
         IS
         select OBJECT_NAME from user_objects
         where object_type in ('TABLE')
         and object_name not like '%AUDIT_DDL%'
         AND object_name not like 'MD_%'
         AND object_name not like 'EXT_%'
         AND object_name not like 'STG_%'
         AND object_name not like 'SYS_%'
         AND object_name not like 'TMP_%'
         AND object_name not like 'TEMP_%'
         order by 1;
         v_count     NUMBER :=0;
         query_str VARCHAR2(1000);
    BEGIN
         FOR table_name IN table_list
         LOOP
              query_str :='SELECT COUNT(1) FROM  ' || table_name.OBJECT_NAME;
    dbms_output.put_line(query_str);
              dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME );
              v_count:= execute immediate query_str;
              dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME || ', Count ' || v_count );
         END LOOP;
    END;
    I know I am doing wrong in the bold lines. But not sure how to fix it. Please help. Thanks in advance.

    Hi,
    Welcome to the forum!
    What you posted is basically right, assuming you really want to do dynamic SQL t all.
    The only problem with
    961618 wrote:
              query_str :='SELECT COUNT(1) FROM  ' || table_name.OBJECT_NAME; would be if the object name included special characters (such as single-quotes) or lower-case letters. To avoid any possible problems, I would put the object name inside double-quotes:
    ...     query_str := 'SELECT COUNT (*) FROM "' || table_name.OBJECT_NAME
                                               || '"';
              v_count:= execute immediate query_str;
    The correct syntax is
    execute immediate query_str INTO v_count;V_count will be the number of rows in a single table. Keep another variable (say total_v_count) that keeps the total count so far.
    Do you really need dynamic SQL?
    SELECT     SUM (num_rows)     AS total_rows
    FROM     user_tables
    WHERE     table_name     NOT_LIKE '%AUDIT_DDL%
    AND     ...
    ;gets the same information, accurate as of the last time statistics were gathered, and some of the numbers may be approximate. Depending on how you use the results, that may be good enough for you. If you actually have 10,000,123 rows, and the query says you have 10,000,000, does it really matter?

  • How can we find the most usage and lowest usage of table in Sql Server by T-SQL

    how can we find the most usage and lowest usage of table in Sql Server by T-SQL
    The table has time stamp column
    StartedOn datetime
    EndedOn datetime

    The Below query has been used , but the textdata column doesnot include the name of the table ServiceLog.
    SELECT
    FROM
    databasename,
    duration
    fn_trace_gettable('F:\Program
    Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Log\log_148.trc',
    default)
    WHERE
    DATABASENAME='ZTCFUTURE'
    AND TEXTDATA
    IS
    NOT
    NULL
    --AND TEXTDATA LIKE 'SERVICE%'
    order
    by cpu
    desc; 

Maybe you are looking for