How to setup trigger based audit? [duplicate] - sql

This question already has answers here:
Log record changes in SQL server in an audit table
(7 answers)
Closed 2 years ago.
I have a table Employee:
CREATE TABLE [dbo].[Employee]
(
[EmployeeCode] [int] NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[Position] [varchar](30) NULL
)
I want to log changes in Employee_Audit table every time there's a change in Position (along with the Old Position, New Position and Timestamp) in Employee table.
CREATE TABLE [dbo].[Employee_Audit]
(
[EmployeeCode] [int] NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[PositionOld] [varchar](30) NULL,
[PositionNew] [varchar](30) NULL,
[Date] [datetime] NULL
)
How do I achieve this?

You basically need an UPDATE trigger that checks if the Position value has changed - and if so, records the details into Employee_Audit:
CREATE OR REPLACE trgEmployeeUpdate
ON dbo.Employee
AFTER UPDATE
AS
BEGIN
-- based on the Inserted and Deleted pseudo tables, join the rows
-- that were updated and look for changes in "Position"
INSERT INTO dbo.Employee_Audit (EmployeeCode, FirstName, LastName, Email,
PositionOld, PositionNew, [Date])
SELECT
i.EmployeeCode, i.FirstName, i.LastName, i.Email,
d.Position, i.Position, SYSDATETIME()
FROM
Inserted i
INNER JOIN
Deleted d ON i.EmployeeCode = d.EmployeeCode
WHERE
i.Position <> d.Position -- Position has changed
END

In addition to trigger option #marc_s mentioned, If you want to not just consider position, and considering all column changes auditing, below options provide you to do auditing, without any specific programming need. You can see whether it fits for your needs.
you can think of SQL Server Temporal Tables. Read on SQL Server Temporal Tables on MSDN. They provide transparent way to auditing the row changes.
You also have Change Data Capture option to track the historical changes for columns. Change Data Capture on MSDN

Related

Dynamic SQL table creation - invalid object after execution?

I am trying to create a table that dynamically pulls the starting IDENTITY ID based on a variable from another table. The SQL executes successfully but afterwards, I am unable to find my temporary table. The DBCC CHECKIDENT brings back Invalid object name '#address_temp'.
IF OBJECT_ID('tempdb.dbo.#address_temp', 'U') IS NOT NULL
DROP TABLE #address_temp
DECLARE #address_temp_ID VARCHAR(MAX)
SET #address_temp_ID = (SELECT MAX(ID) FROM [PRIMARYDB].[dbo].[ADDRESS])
DECLARE #SQLBULK VARCHAR(MAX)
SET #SQLBULK = 'CREATE TABLE #address_temp(
[ID] [int] IDENTITY(' + #address_temp_ID + ',1) NOT NULL,
[NAME] [varchar](128) NOT NULL,
[ADDRESS1] [varchar](128) NOT NULL,
[ADDRESS2] [varchar](128) NULL,
[CITY] [varchar](128) NULL,
[STATE_ID] [smallint] NULL,
[ZIP] [varchar](10) NOT NULL,
[COUNTY] [varchar](50) NULL,
[COUNTRY] [varchar](50) NULL
CREATE CLUSTERED INDEX pk_add ON #address_temp ([NAME])'
EXEC (#SQLBULK)
DBCC CHECKIDENT('#address_temp')
Table names that start with # are temporary tables and SQL Server treats them differently. First of all they are only available to the session that created them (this is not quite true since they you can find them in the temp name space but they have a unique system generated name)
In any case they won't persist so you don't need to drop them (that happens auto-magically) and you certainly can't look at them after your session ends.... they are gone.
Don't use a temp table, take out the # in the name. Things will suddenly start working.

Nested SQL Queries 3 levels

I am using MS Access and having troubles writing a query(s) to get my end result. Maybe someone can lend a hand.
I have Projects, Tasks and SubTasks tables. Each table has a related table for "Assignees". meaning a project could be assigned to an employee but the child tasks could be assigned to a different employee and still further the subtasks could then be assigned to other employees.
Now, when displaying this on screen, and I query for an employee that has been assigned to any project/Task/Subtask. I need that data to display but not other data. So for instance if the employee I query for only has been assigned to a task, then that project and task should display, but no additional projects/tasks/ and no subtasks. Likewise, if I query for an employee that only has been assigned to a subtask, then I only want to see the associated project and task. I think I can complete this with a series of queries...i think... but is there a slick method I can use to create this data.
Simply a select query with a series of joins could possibly work, but it doesnt because when an employee has been assigned to a subtask only and not to a project or task.
Thanks for any assistance!
Updated with additional information:
Table Structures:
CREATE TABLE [dbo].[Projects](
[ProjectID] [int] IDENTITY(1,1) NOT NULL,
[ProjectName] [varchar](100) NULL,
[ClientID] [int] NULL,
CREATE TABLE [dbo].[PM_ProjectAssignee](
[AssigneeID] [int] IDENTITY(1,1) NOT NULL,
[ProjectID] [int] NULL,
[EmployeeID] [int] NULL,
CREATE TABLE [dbo].[PM_ProjectTasks](
[ProjectTaskID] [int] IDENTITY(1,1) NOT NULL,
[ProjectID] [int] NULL,
[TaskID] [smallint] NULL,
CREATE TABLE [dbo].[PM_TaskAssignee](
[AssigneeID] [int] IDENTITY(1,1) NOT NULL,
[ProjectTaskID] [int] NULL,
[EmployeeID] [int] NULL,
CREATE TABLE [dbo].[PM_ProjectSubTasks](
[ProjectSubTaskID] [int] IDENTITY(1,1) NOT NULL,
[ProjectTaskID] [int] NULL,
[SubTaskDesc] [varchar](255) NULL,
CREATE TABLE [dbo].[PM_SubTaskAssignee](
[AssigneeID] [int] IDENTITY(1,1) NOT NULL,
[ProjectSubTaskID] [int] NULL,
[EmployeeID] [int] NULL,
With regards to queries I have tried...alot. I was implementing a scenario where I ended up with about a half dozen different queries all culminating into one (some of the queries where built with code to allow filtering) However the last one tried was:
SELECT ProjectID, ProjectName, EmployeeID, ProjectTaskID, EmployeeID, Association, ProjectSubTaskID, EmployeeID
FROM (qrTest3_Project LEFT JOIN qrTest2_Task ON qrTest3_Project.ProjectID = qrTest2_Task.ProjectID) LEFT JOIN qrtest1_SubTask ON qrTest2_Task.ProjectTaskID = qrtest1_SubTask.Association
WHERE (((qrTest3_Project.EmployeeID)=8)) OR (((qrTest2_Task.EmployeeID)=8)) OR (((qrtest1_SubTask.EmployeeID)=8));
the above query included other queries that simply joined each project/task/subtask to their respective assignee table. I can post those as well if needed.
I hope that provides the additional information you need? If not, happy to provide more.
Thanks!
I think I may have figured it out..as I sort of suspected, I was making it a bit more difficult then it needed to be. Simply joins really with criteria gives me the data I need and can work with.
SELECT PM_ProjectAssignee.ProjectID, PM_ProjectTasks.ProjectTaskID, PM_ProjectSubTasks.ProjectSubTaskID
FROM (((PM_ProjectAssignee
LEFT JOIN PM_ProjectTasks
ON PM_ProjectAssignee.ProjectID = PM_ProjectTasks.ProjectID)
LEFT JOIN PM_ProjectSubTasks
ON PM_ProjectTasks.ProjectTaskID = PM_ProjectSubTasks.ProjectTaskID)
LEFT JOIN PM_TaskAssignee
ON PM_ProjectTasks.ProjectTaskID = PM_TaskAssignee.ProjectTaskID)
LEFT JOIN PM_SubTaskAssignee
ON PM_ProjectSubTasks.ProjectSubTaskID = PM_SubTaskAssignee.ProjectSubTaskID
WHERE (((PM_ProjectAssignee.EmployeeID)=14))
OR (((PM_TaskAssignee.EmployeeID)=14))
OR (((PM_SubTaskAssignee.EmployeeID)=14))
GROUP BY PM_ProjectAssignee.ProjectID, PM_ProjectTasks.ProjectTaskID, PM_ProjectSubTasks.ProjectSubTaskID;

Implementing custom fields in a database for large numbers of records

I'm developing an app which requires a user defined custom fields on a contacts table. This contact table can contain many millions of contacts.
We're looking at using a secondary metadata table which stores information about the fields, along with a tertiary value table which stores the actual data.
Here's the rough schema:
CREATE TABLE [dbo].[Contact](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](max) NULL,
[MiddleName] [nvarchar](max) NULL,
[LastName] [nvarchar](max) NULL,
[Email] [nvarchar](max) NULL
)
CREATE TABLE [dbo].[CustomField](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FieldName] [nvarchar](50) NULL,
[Type] [varchar](50) NULL
)
CREATE TABLE [dbo].[ContactAndCustomField](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ContactID] [int] NULL,
[FieldID] [int] NULL,
[FieldValue] [nvarchar](max) NULL
)
However, this approach introduces a lot of complexity, particularly with regard to importing CSV files with multiple custom fields. At the moment this requires a update/join statement and a separate insert statement for every individual custom field. Joins would also be required to return custom field data for multiple rows at once
I've argued for this structure instead:
CREATE TABLE [dbo].[Contact](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](max) NULL,
[MiddleName] [nvarchar](max) NULL,
[LastName] [nvarchar](max) NULL,
[Email] [nvarchar](max) NULL
[CustomField1] [nvarchar](max) NULL
[CustomField2] [nvarchar](max) NULL
[CustomField3] [nvarchar](max) NULL /* etc, adding lots of empty fields */
)
CREATE TABLE [dbo].[ContactCustomField](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FieldIndex] [int] NULL,
[FieldName] [nvarchar](50) NULL,
[Type] [varchar](50) NULL
)
The downside of this second approach is that there is a finite number of custom fields that must be specified when the contacts table is created. I don't think that's a major hurdle given the performance benefits it will surely have when importing large CSV files, and returning result sets.
What approach is the most efficient for large numbers of rows? Are there any downsides to the second technique that I'm not seeing?
Microsoft introduced sparse columns exactly for this type of problems. Tha point is that in a "classic" design you end up with large number of columns, most of the NULLs for any particular row. Same here with sparse columns, but NULLs don't require any storage. Moreover, you can create sets of columns and modify sets with XML.
Performance- and storage-wise, sparse columns are the winner.
http://technet.microsoft.com/en-us/library/cc280604.aspx
uery performance. Query performance for any "property bag table" approach is funny and comically slow - but if you need flexibility you can either have a dynamic table that is changed via an editor OR you have a property bag table. So when you need it, you need it.
But expect the performance to be slow.
The best approach would likely be a ContactCustomFields table which has - fields that are determined by an editor.

SQL Historical Changes

I have been trying to wrap my head around this for some time now and just can't seem to find a good solution so I am consulting the overflow. I have a table which looks a little like this:
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NOT NULL,
[Title] [varchar](255) NULL,
[QueueId] [int] NOT NULL,
[SupervisorId] [int] NULL,
Employees are moved from one queue to another queue at different time intervals. how should I structure my second table so I can see not only how many people where in a queue at a specific time interval but also who they were?
I would say the table will look like this:
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[QueueId] [int] NOT NULL,
[Start] [datetime] NOT NULL,
[End] [datetime] NOT NULL
The unfortunate thing is you have to go back and "end date" the prior row. If I am the one doing it, I will skip the [End] and create a view on top of the table that will supply the [End].
The view will look like
SELECT A.[EmployeeId]
, A.[QueueId]
, A.[Start]
, COALESCE(MIN([B.Start]),'9999-12-31') as [END]
FROM Table A
LEFT OUTER JOIN Table B
ON A.[EmployeeId] = B.[EmployeeId]
AND A.[Start] < B.[Start]
If you do it this way, you cannot use BETWEEN when joining to this view. You have to say >= [Start] and < [END]. Anyway, it's safer and more robust since you don't have to decide on a date/time "rounding" unit.
queueid int
status varchar(20)
start datetime
end datetime
Your 2nd table should have a primary key, datetime, and count columns. However, you will need a 3rd table that lists the people in the queue, since the count & list reside in different hierarchical levels.

How do I insert into two tables all at once in a stored procedure? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I INSERT data into two tables simultaneously in SQL Server?
Doing a project for school so any help would be great thank you!
I have two tables - how do I insert into two tables? So both tables are linked.
First table is called Customer with primary key called CID that auto increments
CREATE TABLE [dbo].[Customer](
[CID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](255) NOT NULL,
[FirstName] [varchar](255) NOT NULL,
[MiddleName] [varchar](255) NULL,
[EmailAddress] [varchar](255) NOT NULL,
[PhoneNumber] [varchar](12) NOT NULL
CONSTRAINT [PK__CInforma__C1F8DC5968DD69DC] PRIMARY KEY CLUSTERED
(
And a second table called Employment that has a foreign key linked to the parent table
CREATE TABLE [dbo].[Employment](
[EID] [int] IDENTITY(1,1) NOT NULL,
[CID] [int] NOT NULL,
[Employer] [varchar](255) NOT NULL,
[Occupation] [varchar](255) NOT NULL,
[Income] [varchar](25) NOT NULL,
[WPhone] [varchar](12) NOT NULL,
CONSTRAINT [PK__Employme__C190170BC7827524] PRIMARY KEY CLUSTERED
(
You need to do something like this:
DECLARE #NewID INT
INSERT INTO Customer(LastName,FirstName,......) VALUES(Value1, Value2, .....)
SELECT #NewID = SCOPE_IDENTITY()
INSERT INTO Employment(CID,Employer,.....) VALUES(#NewID, ValueA,..........)
SCOPE_IDENTITY: Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.