Trigger Is Deleting Entries In Audit Table?

Aug 30, 2013

The following is the trigger which create a row in the audit table when a single deletion is occurred.

ALTER TRIGGER [dbo].[TRG_Delete_tbl_attendance]
ON [dbo].[tbl_attendance]
AFTER DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.

[code]....

I am trying to create a trigger which should prevent the bulk deletion. The following is the trigger which I have written, it is preventing the bulk deletion. But the problem is, it is removing the single deletion entries in the audit table. I want audit table to hold back the single deletion entries without allowing the bult deletion

ALTER TRIGGER [dbo].[TRG_Delete_Bulk_tbl_attendance]
ON [dbo].[tbl_attendance]
AFTER DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

[code]....

View 1 Replies


ADVERTISEMENT

Appending And Deleting Entries In Table

Jul 11, 2014

I have a question on appending and deleting entries in mysql table. This is my sample table.

table name: details

id_name | model | mode | media| first | end | id | level |
+--------------------+-------+---------+-----+-------+-------+--------+--------+
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 14684 | 6255 | q |
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 14838 | 6255 | q |
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 15236 | 6255 | q |
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 15423 | 6255 | q |
| PSK_30s1207681L002 | 1 | 1 | N | 14026 | 15627 | 6255 | q |

[Code] ....

I have numerous entries of same id name belonging to same median number.However,I want to only retain the entries having the longest first and end position and discard the remaining entries

E.g. for id name ="PSK_30s1207681L002" AND median = 5 we have four entries

id_name | model | mode | media| first | end | id | level |
+--------------------+-------+---------+-----+-------+-------+--------+--------+
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 14684 | 6255 | q |
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 14838 | 6255 | q |
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 15236 | 6255 | q |
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 15423 | 6255 | q |
| PSK_30s1207681L002 | 1 | 1 | N | 14026 | 15627 | 6255 | q |

But I want to retain only the one having longest first and end points ie

| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 15423 | 6255 | q |
| PSK_30s1207681L002 | 1 | 1 | N | 14026 | 15627 | 6255 | q |

Here ,since for id name ="PSK_30s1207681L002" & median = N we have only 1 entry I want retain that one.

My final output in mysql table should look like this.

id_name | model | mode | media| first | last | id | level |
| PSK_30s1207681L002 | -1 | 1 | 5 | 14026 | 15423 | 6255 | q |
| PSK_30s1207681L002 | 1 | 1 | N | 14026 | 15627 | 6255 | q |
| PSK_30s1207681L002 | -1 | 1 | 3 | 14033 | 15627 | 6255 | q |
| PSK_30s1207681L002 | -1 | 1 | T0 | 15550 | 16050 | 6255 | q |
| PSK_30s1189731L001 | -1 | 1 | 3 | 999 | 7531 | 9808 | c |
| PSK_30s1189731L001 | -1 | 1 | 5 | 6609 | 8257 | 9808 | c |

[Code] ....

Is there anything that I could do to append it?

View 1 Replies View Related

Trigger Doesn't Log Into The Audit Table If The Column Of Table Has Trigger On Is Null

Jan 23, 2008



Hi,

I have a trigger set on TABLE1 so that any update to this column should set off trigger to write to the AUDIT log table, it works fine otherwise but not the very first time when table1 has null in the column. if i comment out

and i.req_fname <> d.req_fname from the where clause then it works fine the first time too. Seems like null value of the column is messing things up

Any thoughts?


Here is my t-sql


Insert into dbo.AUDIT (audit_req, audit_new_value, audit_field, audit_user)

select i.req_guid, i.req_fname, 'req_fname', IsNull(i.req_last_update_user,@default_user) as username from inserted i, deleted d

where i.req_guid = d.req_guid

and i.req_fname <> d.req_fname



Thanks,
leo

View 7 Replies View Related

Generic Audit Trigger CLR C#(Works When The Trigger Is Attached To Any Table)

Dec 5, 2006

This Audit Trigger is Generic (i.e. non-"Table Specific") attach it to any tabel and it should work. Be sure and create the 'Audit' table first though.

The following code write audit entries to a Table called
'Audit'
with columns
'ActionType' //varchar
'TableName' //varchar
'PK' //varchar
'FieldName' //varchar
'OldValue' //varchar
'NewValue' //varchar
'ChangeDateTime' //datetime
'ChangeBy' //varchar

using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public partial class Triggers
{
//A Generic Trigger for Insert, Update and Delete Actions on any Table
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AuditTrigger", Event = "FOR INSERT, UPDATE, DELETE")]

public static void AuditTrigger()
{
SqlTriggerContext tcontext = SqlContext.TriggerContext; //Trigger Context
string TName; //Where we store the Altered Table's Name
string User; //Where we will store the Database Username
DataRow iRow; //DataRow to hold the inserted values
DataRow dRow; //DataRow to how the deleted/overwritten values
DataRow aRow; //Audit DataRow to build our Audit entry with
string PKString; //Will temporarily store the Primary Key Column Names and Values here
using (SqlConnection conn = new SqlConnection("context connection=true"))//Our Connection
{
conn.Open();//Open the Connection
//Build the AuditAdapter and Mathcing Table
SqlDataAdapter AuditAdapter = new SqlDataAdapter("SELECT * FROM Audit WHERE 1=0", conn);
DataTable AuditTable = new DataTable();
AuditAdapter.FillSchema(AuditTable, SchemaType.Source);
SqlCommandBuilder AuditCommandBuilder = new SqlCommandBuilder(AuditAdapter);//Populates the Insert command for us
//Get the inserted values
SqlDataAdapter Loader = new SqlDataAdapter("SELECT * from INSERTED", conn);
DataTable inserted = new DataTable();
Loader.Fill(inserted);
//Get the deleted and/or overwritten values
Loader.SelectCommand.CommandText = "SELECT * from DELETED";
DataTable deleted = new DataTable();
Loader.Fill(deleted);
//Retrieve the Name of the Table that currently has a lock from the executing command(i.e. the one that caused this trigger to fire)
SqlCommand cmd = new SqlCommand("SELECT object_name(resource_associated_entity_id) FROM
ys.dm_tran_locks WHERE request_session_id = @@spid and resource_type = 'OBJECT'", conn);
TName = cmd.ExecuteScalar().ToString();
//Retrieve the UserName of the current Database User
SqlCommand curUserCommand = new SqlCommand("SELECT system_user", conn);
User = curUserCommand.ExecuteScalar().ToString();
//Adapted the following command from a T-SQL audit trigger by Nigel Rivett
//http://www.nigelrivett.net/AuditTrailTrigger.html
SqlDataAdapter PKTableAdapter = new SqlDataAdapter(@"SELECT c.COLUMN_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = '" + TName + @"'
and CONSTRAINT_TYPE = 'PRIMARY KEY'
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME", conn);
DataTable PKTable = new DataTable();
PKTableAdapter.Fill(PKTable);

switch (tcontext.TriggerAction)//Switch on the Action occuring on the Table
{
case TriggerAction.Update:
iRow = inserted.Rows[0];//Get the inserted values in row form
dRow = deleted.Rows[0];//Get the overwritten values in row form
PKString = PKStringBuilder(PKTable, iRow);//the the Primary Keys and There values as a string
foreach (DataColumn column in inserted.Columns)//Walk through all possible Table Columns
{
if (!iRow[column.Ordinal].Equals(dRow[column.Ordinal]))//If value changed
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "U";//U for Update
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the entry
}
}
break;
case TriggerAction.Insert:
iRow = inserted.Rows[0];
PKString = PKStringBuilder(PKTable, iRow);
foreach (DataColumn column in inserted.Columns)
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "I";//I for Insert
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = null;
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
case TriggerAction.Delete:
dRow = deleted.Rows[0];
PKString = PKStringBuilder(PKTable, dRow);
foreach (DataColumn column in inserted.Columns)
{
//Build and Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "D";//D for Delete
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = null;
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
default:
//Do Nothing
break;
}
AuditAdapter.Update(AuditTable);//Write all Audit Entries back to AuditTable
conn.Close(); //Close the Connection
}
}


//Helper function that takes a Table of the Primary Key Column Names and the modified rows Values
//and builds a string of the form "<PKColumn1Name=Value1>,PKColumn2Name=Value2>,......"
public static string PKStringBuilder(DataTable primaryKeysTable, DataRow valuesDataRow)
{
string temp = String.Empty;
foreach (DataRow kColumn in primaryKeysTable.Rows)//for all Primary Keys of the Table that is being changed
{
temp = String.Concat(temp, String.Concat("<", kColumn[0].ToString(), "=", valuesDataRow[kColumn[0].ToString)].ToString(), ">,"));
}
return temp;
}
}

The trick was getting the Table Name and the Primary Key Columns.
I hope this code is found useful.

Comments and Suggestion will be much appreciated.

View 16 Replies View Related

Updating Table - Trigger Duplicate Entries

Jun 12, 2014

I got error while updating a table ,duplicate entries and trigger got fired ..so how to debug the trigger to know duplicate record.

View 1 Replies View Related

Trigger On Table LeaveRegister And Inserting Rows In Audit Table

Oct 22, 2012

I write a insert trigger on my table LeaveRegister(1000 rows) and inserting rows in audit table, but when i inserting a row in LeaveRegister table. In audit table 1000 + 1 rows are inserting every time.

View 6 Replies View Related

Writting Trigger Or Procedure To Delete Duplicate Entries In A Table?

Sep 3, 2007

I am using Sql Server 2000.
I have a customer table with fields - CustId, Name, Address, City, StdCode, Phone.
I used to insert entries in this table from an excel file.
One excel file will contain thousands of customer.
In this table combination of StdCode and Phone should not be repeated.
If I do it in my VB.Net coding.then application gets drastically slow.
So I want to write a procedure or trigger for this.
Here what I will do, I will send all records into database then this trigger or procedure will check for
any existing entry of combination of StdCode and phone. If entry exists then this will delete new entry
or will not allow this new entry.
Is this possible to do using Trigger or stored procedure?

View 5 Replies View Related

Trigger For Deleting Row From Same Table.

May 31, 2002

Hello everybody,
I have problem deleting row from same table using below trigger

CREATE TRIGGER [tDeleteDomain] ON dbo.iMS_Domains
FOR DELETE
AS
IF @@RowCount > 1
BEGIN
ROLLBACK TRAN
RAISERROR ('You can only delete one domain at a time.', 16, 10)
END
DECLARE@DomainID int
SELECT@DomainID = ID
FROMDELETED
DELETE FROMiMS_Domains
WHEREAliasFor = @DomainID

If I am using this trigger I am getting the below error
Server: Msg 217, Level 16, State 1, Procedure tDeleteid, Line 16
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32)

Can anybody give good suggestiong regarding this.

Thanks,
ravi

View 6 Replies View Related

Deleting Entries Under A Category That Is Being Deleted???

Sep 11, 2007

Hello.  I have a simple project using 3 tables: Categories, Subcategories, and Items.  I have just gotten my insert, edit, and delete functions to work, but I've noticed a problem I hope someone can help with:
 When I delete a certain category (lets say "Restaurants"), the subcategories and items that were in that category still remain in the database/table.  (If I delete "Restaurants", the subcategories "Italian", "Seafood", etc - as well as any items in those subcategories - are not deleted).
 So what would I need to do to delete any Subcategory that is in the deleted Category (shares a CategoryID) and then delete all Items in those Subcategories?
 For reference, all Subcategories in a Category have reference to that CategoryID, and all Items in a Subcategory have a "SubcategoryID" field.  I understand that I need to traverse the tables and remove all Subcategories with the CategoryID being deleted, but since the Items do not have a reference to the CategoryID, how would I delete those as well?
 
Thanks to whoever can help me out here!

View 4 Replies View Related

Deleting Unwanted Entries At The Subscriber .

Oct 8, 2002

Hello ,

I have created a publication from SQL Server 7.0 and subscribed the publication it to one of the SQL 2000 server std. edition .

Now there are some entries in the subscription list at the subscriber which need to be deleted .
The list shows the name of the publication , the database name and the date .

I wanted to know hoe can we delete those unwanted entries. If i select the entry and right click on it , there is no delete option .

Are those entries to be deleted from one of the tables at the subscriber or the publisher ? If yes, then what is the name of the table ?

Any ideas ?

Thank you very much .

View 3 Replies View Related

Database Audit Specification To Audit Select On Certain User And Table

Nov 1, 2014

I have made a server security audit and specify from database audit specification to audit "select" on a certain user and on a certain table. I logged in by this user and made the select statement..when i run this query

"select * from sys.fn_get_audit_file('d:Auditaudit1*',null,null)"

It return a value at which time the query has done

after 15 minutes i repeated the same action, i run the audit query and the same result is showed off on the panel.is it suppose to return a list of values by how many times this user has made the select statement on that table ? for example at 5:00 pm then 6:00 pm and so on

View 1 Replies View Related

Audit Trigger

Jun 5, 2007

hi, im kinda new to sql and was just wondering if someone could help.

i need to create a trigger that saves all changes from a table(table1) to an audit table.

-table1-
item_code
item_price
item_description

View 2 Replies View Related

Audit From Trigger

Oct 26, 2007



I wont to get text of statement which chaged actual table.

with this script :




Code Block
if object_id('dbo.mytable') is not null drop table dbo.mytable
go
create table dbo.mytable (f1 varchar(100))
go
alter trigger dbo.ti_mytable on dbo.mytable for insert
as
set nocount on
print 'in trigger'
DECLARE @sql_handle binary(20)
select @sql_handle = sql_handle FROM master.dbo.sysprocesses p (nolock) where spid = @@spid
select @sql_handle, @@spid, [text] FROM ::fn_get_sql(@sql_handle) as statement_text
GO




if I execute



Code Block
insert into mytable values ('test')



I getting text of the trigger. How I can get @sql_handle of original statement ?

View 1 Replies View Related

Create Audit Trigger

Nov 2, 2004

I need to create a simple audit trigger for a table with 12 columns. I need to determine which row was changed. Is there a simple way to do that. The table structure is
ID Integer(4)
barcode(25)
epc_tag(24)
bc_stop_flag(1)
reject_flag(1)
complete_flag(1)
hold_flag(1)
pe_1_flag
pe_2_flag
pe_3_flag
pe_4_flag
pe_5_flag

View 3 Replies View Related

SQL Trigger For Audit Trails

May 29, 2006

I have a trigger on my Table (MyTable). The Trigger saves any changes to mytable. The AuditTrails table has this columns: ID, TableName,PrimaryKey, OLDvalue, NewValue,UserID,DateCreated.

Now, how can i pass the application's UserID (Not the SQL Server User) and save it to the AuditTrails table?

In my .NET Application, if someone delete a record from myTable how can i possibly get the userid of that person using my Audit trail Trigger?

View 5 Replies View Related

Audit Trail Trigger

Jan 21, 2008

Hi all,

I'm trying to create a audit trail trigger. I'm new to SQL Server. For simplicity sake, let's just say I have a table like the following:

Table1

FieldA
FieldB

And the audit table is:

Table1_Audit
FieldA
FieldB
Operation (Insert/Update/Delete)
Operator (Username)
Op_Date (GetDate())

Ok, simple enough. Now, I'm using Studio Express and there are several templates available. By default this is the one I get:


SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO


CREATE TRIGGER <Schema_Name, sysname, Schema_Name>.<Trigger_Name, sysname, Trigger_Name>

ON <Schema_Name, sysname, Schema_Name>.<Table_Name, sysname, Table_Name>

AFTER <Data_Modification_Statements, , INSERT,DELETE,UPDATE>

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;

-- Insert statements for trigger here

END

GO


Not sure if I need all of this information? Examples I've found on the web look very confusing...ugh. I looking for simple (if possible).

Many thanks in advance,

Mark

View 2 Replies View Related

Deleting The Master Table Withour Deleting The Child Tables

Aug 9, 2007

Hi
i have to delete the master table data without deleting the child table records,is there any solution for this,  parent table has relation with the child table.
regards
vinod.t.v

View 9 Replies View Related

DELETE Audit Trigger With BLOBs

Oct 14, 1999

Greetings

I'm clear about the use of a DELETE trigger to "move" your deleted record to a second database as a sort of recycle bin.

But SS7 has the limitation, and it's mentioned in BOL, that it cannot reference your TEXT, NTEXT or IMAGE fields in the DELETED table. It says to join the original table with DELETED to get at those fields.

The only problem is the original table's record has been deleted! Even though the transaction has not yet been COMMITTED.

Here's my Trigger:

CREATE TRIGGER AuditTest ON Activity FOR DELETE AS

INSERT AuditDB.dbo.Activity
SELECT Activity.* FROM Activity INNER JOIN Deleted
ON Activity.ActivityID = Deleted.ActivityID

And for discussion, here's my Table:

ActivityID uniqueidentifier
OrgId uniqueidentifier
Title varchar(600
Active bit
Comments text
LastUpdate datetime

Any suggestions? Has anyone been able to implement a DELETE Audit
Trigger on a table with BLOBs?

Thanks,

-Rich

Richard Hundhausen
Stuttgart, Germany

View 3 Replies View Related

Audit Trigger In Stored Procedure?

Dec 7, 2011

I have a requirement to audit tables in a SQL Server database. The tables are dynamically created when the application creates a form and the table holds the form data. So my plan is this, I have worked out the audit table (static) and the trigger. What i'm having issues with is getting the trigger to create from within the stored procedure. So just to recap: the user creates a form in the app, this creates a table and should call this stored procedure. The stored procedure creates the trigger on that table (which begins auditing that table, inserting to the static audit table based on the table name being passed into the stored procedure).

Where im at: I can create the stored procedure. When i go to run the stored procedure, I get the errors after passing the table as a value.

In my opinion it's an error with the correct number of single ticks, but not sure.

The Code:
USE [AdventureWorks]
GO
/****** Object: StoredProcedure [dbo].[spReplaceAuditTrigger] Script Date: 12/06/2011 15:28:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC spReplaceAuditTrigger( @PassedTableName as NVarchar(255) ) AS

[code].....

View 3 Replies View Related

SQL Audit : CLR Trigger Vs TSQL Triggers

Nov 26, 2007

Hi,
I am trying to figure out which of these option is best suited for auditing. Although each one of them has its own pros/cons.
CLR trigger is easy to write and can be made generic so that it fits for any table required to be audited.
I tried both the option in test database and i found the CLR trigger performed poorly.
Results were :
For table A (3 columns) with TSQL trigger took less than a sec for 2500 sequential inserts.
While table B (3 columns) having same structure with CLR trigger took more than 20 sec for 2500 sequential inserts.

Has anybody done performance comparision of this 2 approaches ?
Please share results if any.

I wanted to validate that is my findings correct so that i select best optimized approach.

Thanks,
Jignesh

View 1 Replies View Related

Incorrect Use Of Update Trigger For Audit Purpose

Jan 24, 2001

I have a update trigger on a table which fires trapping the userid and time in the same record. The code is below. The tirgger only works if I have the recursive triggers option unchecked on databae properties. Is the way I am trying the only way to accomplish this in the update trigger or is there an more efficient way. Thanks

CREATE trigger tr_cmsUpdt_MARS on dbo.PATIENT_MEDICATION_DISPERSAL_ for UPDATE as
-- updates record with sql user and timestamp
--created 11-28-00 tim cronin
DECLARE @muser varchar(35),
@rec_lock_status int,
@ptacpt_status int
set @muser = current_user
begin
UPDATE PATIENT_MEDICATION_DISPERSAL_
set MODIFIED_BY = @muser,
MODIFIED_TS = getdate()
from deleted dt
WHERE PATIENT_MEDICATION_DISPERSAL_.RECORD_ID = dt.RECORD_ID
end
GO
SET QUOTED_IDENTIFIER OFF SET ANSI_NULLS ON
GO

View 2 Replies View Related

Transact SQL :: Simple Trigger To Audit Who When Is Changing A Specific Column

Jul 6, 2015

I need a trigger to know who and when a char(1) column is changed.  Would like to write the audit trail to its own table I can query and record before and after values.

DDL:

CREATE TABLE [dbo].[Test](
[Customer] [varchar](12) NULL,
[Active] [char](1) NULL DEFAULT ('N') --Must use char 1 b/c more than 2 possible values
)

Insert into Test (Customer, Active) Values ('Acme','Y')..I want trigger to tell me whowhenwhere this value was changed.  If using sql auth capture client windows id if possible and write to audit table Update Test set Active = 'N'

View 6 Replies View Related

Creating A Trigger To Check Before Deleting A Record

Jun 12, 2008

I am using the tables created by the aspnet_regsql.exe tool for security.  Basically, I need to ensure that an account named Administrator is never deleted.  I also have a role named administrator, and I need to make sure that Administrator is never removed from the administrator role.Can I create a trigger to ensure that the Administrator is never deleted and that the Administrator is never removed from the Administrator role?  I know it will probably be two separate triggers: one on the aspnet_users table and one on the aspnet_usersinroles table.Thanks a lot for the help!

View 1 Replies View Related

Create An Extra Table (for Audit Purpose) For Every Existing Table In A Database

Mar 28, 2008

Hi all, please help. I m trying to create an "empty" table from existing table for the audit trigger purpose.
For now, i am trying to create an empty audit table for every table in a database named "pubs", and it's seem won't work.
Please advise.. Thanks in advance.

Here is my code:





Code Snippet

USE pubs

DECLARE @TABLE_NAME sysname
DECLARE @AUDIT_TABLE VARCHAR(50)

SELECT @TABLE_NAME= MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_TYPE= 'BASE TABLE'
AND TABLE_NAME NOT LIKE 'audit%'
AND TABLE_NAME!= 'sysdiagrams'
AND TABLE_NAME!= 'Audit'
AND TABLE_NAME = 'sales'

WHILE @TABLE_NAME IS NOT NULL
BEGIN

SELECT @TABLE_NAME= MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables
WHERE TABLE_NAME> @TABLE_NAME
AND TABLE_NAME = 'sales'

SELECT @AUDIT_TABLE = 'Audit'+''@TABLE_NAME''


SELECT * INTO @AUDIT_TABLE
FROM @TABLE_NAME

TRUNCATE TABLE @AUDIT_TABLE
ALTER TABLE @AUDIT_TABLE ADD UserAction Char(10),AuditStartTime Char(50),AuditUser Char(50)


SELECT @TABLE_NAME= MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables
WHERE TABLE_NAME> @TABLE_NAME
AND TABLE_TYPE= 'BASE TABLE'
AND TABLE_NAME!= 'sysdiagrams'
AND TABLE_NAME!= 'Audit'
AND TABLE_NAME NOT LIKE 'audit%'

END
Thanks. ..

View 6 Replies View Related

No Further Entries Of A Value In Table

Mar 30, 2012

I have a table which stores phone numbers of a customer in a table.

Say this table is as below

CustomerName - PhoneNumber
Customer 1 - Phone number 1
Customer 2 - Phone number 2
Customer 2 - Phone number 3
Customer 3 - Phone number 4

What would be the best approach to prevent adding another entry against Customer 2. I should be able to add new customers and add multiple phone number against all other Customers. The restriction should be only against Customer 2.

View 4 Replies View Related

Getting Random Table Entries

Jan 20, 2008

Hi,I have a  form that should show 2 pictures based on table entries.I want those 2 pictures to be randomly selected based on a database table. So, my table has all the entries, and I want to pull out a random entry that has been approved to display it.Can someone help me with the sql query?I can do SELECT VoteId FROM tblVotes WHERE Approved=True..But how do I make selection a random one that changes every time the user gets another entry? 

View 2 Replies View Related

Entries In UPPER In A Table

Mar 27, 2001

Is there a way I can have all entries in a table automatically in caps once entered by user, import or any other way ?


Thanks a lot in advance.

-PFD

View 2 Replies View Related

How To Know The Order Of Entries In A Table

Jul 5, 2007

For example some data has entered into a table in a random manner i.e the pk filed value is not in a serial fashion.Is there any table or index that holds the entries of rows into a particular table as entered .

i.e
'some_table' has data like this

3,entry3
2,entry2
4,entry4
1,entry1

I want some DB table or Index that holds data like this about above 'some_table'

row_id .... .... ....
1
2
3
4

here 1 refers to entry of the first column in 'some_table' i.e 3,entry3
and so on...

View 2 Replies View Related

Show Changes Between Records In Main Table And Audit Table

Aug 2, 2006

Hallo
i have two tables, MainTable and MainTableAudit: the second one keeps DML auditing via triggers.
I'm trying to build a query to highlight changes occurred to fields between the MainTable record and its audited records in MainTableAudit, for example, let's suppose i entered an item with some wrong attributes, and edited it three times:
MainTable record contains the latest and current version
ID002|Hitchhikers Guide to the Galaxy|Sci-fi|240 pages
MainTableAudit contains edited ID002 versions
ID002|Hitchhikers Guide to the Galaxy|Sci-fi|232 pages|2006-07-08 08:32:12
ID002|Hitchhikers Guide to the Galaxy|Sci-fi|212 pages|2006-05-08 10:54:02
ID002|Hitchhikers Guide to Galaxy|Sci-fi|222 pages|2006-07-04 11:42:16

I would like to build a report like this:
first insertion: Hitchhikers Guide to Galaxy|Sci-fi|222 pages
modified on 2006-07-04 11:42:16: field "Title" changed from "Hitchhikers Guide to Galaxy" to "Hitchhikers Guide to the Galaxy", field "PageNo" changed from "222" to "212"
modified on 2006-05-08 10:54:02: field "PageNo" changed from "212" to "232"
modified on 2006-07-08 08:32:12: field "PageNo" changed from "232" to "240"
current version: Hitchhikers Guide to the Galaxy|Sci-fi|240 pages

i'd prefer to use T-SQL and keep all into a single place (a view or storedprocedure), or at least to use reporting services; btw i would like to avoid coding web pages or hosted applications.

View 1 Replies View Related

Duplicate Entries In The Resulting Table

Sep 20, 2007

Hi! I am joining 3 tables in SQL , I am getting the results I want exept it's duplicated. So the resultinmg table fom my stored procedure has 3 rows that have the same bulletin. How do I filter the storedprocedure to output only the rows that don't have duplicate entries for the column 'Bulletin' Thanks.
Here is my stored procedure:PROCEDURE [dbo].[spGetCompBulletins]
@Userid uniqueidentifier OUTPUT,@DisplayName varchar(200)
 
AS
 
SELECT *
FROM dbo.UserProfile INNER JOIN
dbo.bulletins ON dbo.UserProfile.UserId = dbo.bulletins.Userid INNER JOINdbo.Associations ON dbo.Associations.BusinessID = dbo.bulletins.Userid WHERE UserProfile.DisplayName=@DisplayName
and Userprofile.Userid = @Userid ORDER BY Bulletins.Bulletin_Date
Return

View 7 Replies View Related

Save DELETED Entries To New Table

Mar 23, 2008

Hi all
I would like to know if its possible to "Save" records when they get deleted.
For example: I have a table, tblUsers, with coulmns, UserID, Name, Surname, etc...
In VWD I've created a GridView which shows everything on a webpage. I've also added a confirm return('Are you sure you want to delete the user?') option in OnClientClick field. What i want to achieve is, have some sort of log file, or log table if you want to call it that, of which users has been deleted by the end user. So, in later stages, i can see who deleted who, when, where, etc... - by building a report or view.
All this should go to a seperate database or seperate table, it doesnt really matter.
My delete query:DELETE FROM [tblUsers] WHERE [UserID] = @UserID

View 9 Replies View Related

Prevent Duplicate Entries In A Table

Nov 11, 2003

I have an ASP.Net Web appplication with a Back-End SQL DB. There are 3 Tables; Users, Groups, and GroupMember.

The GroupMember table is used to link Users to Groups and consists of just two fields; userID and GroupID.

Here is a sample of some data:

User1 Group1
User1 Group2
User2 Group2
User3 Group1
User3 Group3

Users can belong to multiple Groups. However, you shouldn't be able to have the same user and group comobination more than once. for example:

User1 Group1
User2 Group2
User1 Group1

I can stop this kind of duplicate data entry by doing a lookup first (using asp.net) to see if the entry already exists but this seems cumbersome.

Is there a simpler way to prevent duplicate entries in a table using sql?

Thanks a lot,

Chris

View 3 Replies View Related

How Do I Should Temp Table Entries In SQL Debug Mo

Sep 5, 2007

I am troubling SQL stored procedures. The SP has temp table created to contain data. How can I populate the temp table in the SQL debug mode?

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved