Trigger ... Is This Valid?
Nov 24, 2004
Is the following valid syntax? Thanks for your help!
IF (SELECT chargeID FROM inserted = 0) BEGIN
END
OR, should I be doing something like this:
DECLARE @thisChargeID as int
SET @thisChargeID = (SELECT chargeID FROM inserted)
IF (@thisChargeID = 0) BEGIN
END
View 14 Replies
ADVERTISEMENT
Jul 24, 2006
hello,everybody ,i use the AnalysisServicesExecuteDDLTask ,but it dap an error "DDL is not valid",i don't konw what is the problem and how to solve?thank you!
View 1 Replies
View Related
Sep 11, 2006
im doing a sum on a table and it either returns a number in decimal format or 'null' . The problem is when it returns null i want it to just make the text say '0.00'. So i did a test on the object that if it returns NULL just print '0.00' but if it is not null it tells me that there is a number there and i want to store that as a decimal and print it out. But i get an error for a type cast when im not it should not even be going to that part of the code. In the code below the first executescaler will return null so it should just go straight to the else. But it gives me the type cast error in the if that shouldnt be seen. The error and code are below. //Borrower NSF FEES
cmd.CommandText = "select sum(itemamount) from postmtdtls where loanid='" + LoanID + "' and Transactioncode = '310'";
object temp = cmd.ExecuteScalar();
if (temp != null)
{
decimal B_NSFFees = ((decimal)cmd.ExecuteScalar());
borrowerPayoff_NSFFees.Text = String.Format("{0:#,#.##}", B_NSFFees).ToString(); //Borrower NSF FEES
}
else
{
borrowerPayoff_NSFFees.Text = "0.00"; //borrowerPayoff_NSFFees.Text = "0.00";
} Server Error in '/WebSite5' Application. Specified cast is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Specified cast is not valid.Source Error: Line 774: if (temp != null)
Line 775: {
Line 776: decimal B_NSFFees = ((decimal)cmd.ExecuteScalar());
Line 777: borrowerPayoff_NSFFees.Text = String.Format("{0:#,#.##}", B_NSFFees).ToString(); //Borrower NSF FEES
Line 778: }Source File: c:ProgrammingFilesWebSite5InvestorPool.aspx.cs Line: 776 Stack Trace: [InvalidCastException: Specified cast is not valid.]
InvestorPool.GetLoanInfo(String LoanID) in c:ProgrammingFilesWebSite5InvestorPool.aspx.cs:776
InvestorPool.MortAccountText(Object sender, EventArgs e) in c:ProgrammingFilesWebSite5InvestorPool.aspx.cs:660
System.Web.UI.WebControls.TextBox.OnTextChanged(EventArgs e) +75
System.Web.UI.WebControls.TextBox.RaisePostDataChangedEvent() +124
System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() +7
System.Web.UI.Page.RaiseChangedEvents() +138
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4507
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42
View 10 Replies
View Related
Feb 27, 2004
Hi,
I'm trying to install MSDE SP3 which I downloaded from MS at http://www.asp.net/msde/.
Following the instructions as best I can I unzipped the file into a Folder now called MSDE located on C: I then went to a command prompt and typed in the command given to start the install:
setup SAPWD=testsite SecurityMode=SQL
Hit enter and the installer started up and ran for a few secs and then came back with
The Instance named specified is invalid
There was no mention of including an instance name or the format for it.
Suggestions please?
Also, if I want to completly uninstall MSDE if I need to how would I do it?
Thanks,
Bob
View 1 Replies
View Related
Apr 7, 2006
Can't seem to find why I'm getting this error: Specified cast is not valid.
Ok, using a stored procedure for SQL Server 2000 and here is the main part of it:
SELECT id, rank, firstName, lastName, service, status, createdTime FROM accessRequest WHERE lastName LIKE @tLastName AND firstName LIKE @tFirstName
And the C# code behind from the class file:
SqlDataReader spResults;
conn.Open();
spResults = command.ExecuteReader();
while( spResults.Read() )
{
AccessRequestSearch request = new AccessRequestSearch( (int)spResults.GetInt32( 0 ), spResults.GetString( 2 ), spResults.GetString( 3 ), spResults.GetString( 1 ), spResults.GetString( 4 ), spResults.GetString( 5 ), Convert.ToDateTime(spResults.GetString( 6 )));
searchResults.Add( request ); // Add to Array List
}
spResults.Close();
The part in red is where I think it's happening because that is what I just added to the request. createdTime in the table is set as DateTime.
Can anyone see what I am missing here?
More info is available if needed.
Thanks,
Zath
View 1 Replies
View Related
Jun 17, 1999
Hello:
I am getting an error:
User id 12 is not a valid user in database Dest_db
While using Database object transfer.
Using mixed security on the source database.
copy data and replace existing data options are selected.
View 1 Replies
View Related
Jan 11, 2006
I have a question regarding the backup to use in case of consistency errors.
I'm backing up my dbs daily and logs hourly with 'verify the integrity of the backup when completed' checked. Today I found out one of my tables has 1 page id error (dbcc checkdb message from yesterday), I'm wondering if I can use yesterday's full backup even if it's done after the dbcc, that way I don't have to apply a lot less log backups. In other words, does or does not the full backup inherit the corruption if it is done after consistency errors and the backup passes the integrity verification.
Thanks,
Markham
View 11 Replies
View Related
Jul 20, 2005
Version 1:--------------------------------If Condition = AUPDATE query 1UPDATE query 2ELSE IF Condition = BUPDATE queryVersion 2:--------------------------------If Condition = ABEGINUPDATE query 1UPDATE query 2ENDELSE IF Condition = BBEGINUPDATE queryENDOr are they functionally equivalent?Thanks
View 2 Replies
View Related
Dec 22, 2006
Hi guys,
I'm having this really strange issue with mirroring.
I've followed the instructions on http://msdn2.microsoft.com/en-us/library/ms191140.aspx to the letter, leaving out the witness server part, as I don't have one.
All works OK, but when activating the mirroring on the principal server I get the usual error 1418 error. I fired up SQL Server Profiler to see what was happening, and the following error emerged.
Connection handshake failed. The certificate used by the peer is invalid due to the following reason: Certificate not yet valid. State 104.
Anyone have any ideas?
View 3 Replies
View Related
May 4, 2007
Hi,
I do not know what I did wrong. I tested a simple function in my custom code and get the error saying "Character is not valid". Any help is appreciated!
Here is the function inside my custom code.
Shared Function test() As string
Dim items As Fields
Return items("DataField1").Value;
End Function
I call the function in the body of my report using: Code.test()
and the error says "There is an error on line 18 of custom code: [BC30037] Character is not valid."
Thanks,
Tabbey
View 6 Replies
View Related
Dec 1, 2006
I get this error in a package which was executing previously. This is in SQLServer OLEDB DATASOURCE
Error at Membership_Other_Payer [DTS.Pipeline]: The index is not valid.
ADDITIONAL INFORMATION:
Exception from HRESULT: 0xC0048004 (Microsoft.SqlServer.DTSPipelineWrap)
This error occurs when I try to open my existing Oledb datasource. I have added some columns in my database
Any body has solution for this?
View 18 Replies
View Related
Jul 11, 2006
sqlConnection1.Open();
System.Data.SqlClient.SqlDataReader Dil1;
Dil1 = sqlDilGetir.ExecuteReader();
ddlDil1.Items.Add(new ListItem("1. Dil", ""));
while (Dil1.Read())
{
ddlDil1.Items.Add(new ListItem(Dil1.GetString(1), Dil1.GetString(0)));
}
Dil1.Close();
sqlConnection1.Close();
View 7 Replies
View Related
Apr 12, 2007
I've build a website with asp.net and on my local machine it run very we. but when I store my website on a server, I have a error : ...error: 25 - Connection String not valid...
This is my connection string on my local machine : "add name="csIyp" connectionString="data source=.SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|iyapason.mdf;User Instance=true" providerName="System.Data.SqlClient" "
And the connection string on my webserver : "add name="csIyp" connectionString="data source= .MSSQLSERVER;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|iyapason.mdf;User Instance=true" providerName="System.Data.SqlClient" "
So, what can I do to solve this probleme.
Thanks !
View 3 Replies
View Related
Aug 11, 2007
GO
CREATE TABLE [dbo].[CmnLanguage]( [Id] [char](2) NOT NULL CONSTRAINT PkCmnLanguage_Id PRIMARY KEY, [UniqueName] [varchar](26) NOT NULL, [NativeName] [nvarchar](26) NOT NULL, [DirectionType] [smallint] NOT NULL, [IsVisible] [bit] NOT NULL, [CreatedDateTime] [datetime] NOT NULL DEFAULT GETDATE(), [ModifiedDateTime] [datetime] NULL)
GO
CREATE TABLE [dbo].[CmnLink]( [Id] [int] IDENTITY(1,1) NOT NULL CONSTRAINT PkCmnLink_Id PRIMARY KEY, [UniqueName] [varchar](52) NOT NULL, [IsVisible] [bit] NOT NULL, [CreatedDateTime] [datetime] NOT NULL DEFAULT GETDATE(), [ModifiedDateTime] [datetime] NULL)
GO
CREATE TABLE [dbo].[CmnLinkCmnLanguage]( [LinkId] [int] NOT NULL CONSTRAINT FkCmnLinkCmnLanguage_LinkId FOREIGN KEY (LinkId) REFERENCES CmnLink(Id) ON DELETE CASCADE, [LanguageId] [char](2) NOT NULL CONSTRAINT FkCmnLinkCmnLanguage_LanguageId FOREIGN KEY (LanguageId) REFERENCES CmnLanguage(Id) ON UPDATE CASCADE ON DELETE CASCADE, [CreatedDateTime] [datetime] NOT NULL DEFAULT GETDATE(), [ModifiedDateTime] [datetime] NULL)
View 4 Replies
View Related
Jan 30, 2004
what i want to achive is the proc sh'd return a master-detail value in one go.
master value should be returned with Out Parameter and detail value as a recordset.
will it return the recordset of detail table as below....
Create Procedure ProductDetail
(
@ProductID int,
@ProductCode varchar(15) OUTPUT,
@ProductName varchar(60) OUTPUT,
@CategoryID int OUTPUT,
@CategoryName varchar(60) OUTPUT,
@Image1 varchar(256) OUTPUT,
@Image2 varchar(256) OUTPUT,
@UnitPrice smallmoney OUTPUT,
@UOMValue numeric(9) OUTPUT,
@UOMName varchar(10) OUTPUT,
@ShippingWeight numeric(9) OUTPUT,
@Directions varchar(1500) OUTPUT,
@Ingrediants varchar(1500) OUTPUT,
@Warnings varchar(1500) OUTPUT,
@ShortDescription varchar(1000) OUTPUT,
@LongDescription varchar(2000) OUTPUT,
@NutritionFacts varchar(1000) OUTPUT,
@SearchKeywords varchar(500) OUTPUT,
@IsTaxable varchar(15) OUTPUT,
@CreatedBy varchar(60) OUTPUT,
@CreatedOn varchar(15) OUTPUT,
@UpdatedBy varchar(60) OUTPUT,
@UpdatedOn varchar(15) OUTPUT,
@Status int OUTPUT
)
AS
SELECT
@ProductCode = ProductCode,
@ProductName = ProductName,
@CategoryID = CategoryID,
@CategoryName = (select CategoryName from mCategory where CategoryID=a.CategoryID),
@Image1 = isnull(Image1,''),
@Image2 = isnull(Image1,''),
@UnitPrice = isnull(UnitPrice,0),
@UOMValue = isnull(UOMValue,0),
@UOMName = isnull(UOMName,''),
@ShippingWeight = isnull(ShippingWeight,0),
@Directions = isnull(Directions,''),
@Ingrediants = isnull(Ingrediants,''),
@Warnings = isnull(Warnings,''),
@ShortDescription = isnull(ShortDesc,''),
@LongDescription = isnull(LongDesc,''),
@NutritionFacts = isnull(NutritionFacts,''),
@SearchKeywords = isnull(SearchKeywords,''),
@IsTaxable = case when isnull(IsTaxable,0)=0 then 'No' else 'Yes' End,
@CreatedBy = isnull((select LName + ',' + FName from mUser where UserID=InsertedBy),''),
@CreatedOn = InsertedOn,
@UpdatedBy = isnull((select LName + ',' + FName from mUser where UserID=UpdatedBy),''),
@UpdatedOn = UpdatedOn,
@Status = Convert(int,isnull(Status,0))
FROM
mProduct a
WHERE
ProductID = @ProductID
SELECT
ID as PricingDetailID,
isnull(PricingFromQnty,0) as PricingFromQnty,
isnull(PricingToQnty,0) as PricingToQnty,
isnull(RangePrice,0) as RangePrice,
Convert(int,isnull(Status,0))as Status
FROM
dProduct
WHERE
ProductID = @CategoryID
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
Regards,
Bhairav
View 4 Replies
View Related
Nov 17, 2005
Here's my code: Dim Cmd as New SQLCommand(sqlString, conn) cmd.CommandType=CommandType.StoredProcedure Breaks Here ----->>cmd.parameters.add(New SQLParameter(@OrdAlias, OrdNum)) cmd.parameters.add(New SQLParameter(@AliasSourceCode, 4))The error says:compilation error - - then, on the line that is in red:Compiler Error Message: BC30037: Character is not valid.I have 'OrdNum' declared globally, and OrdNum is assigned right away in the Page_Load event. I've checked the spelling of the SQL parameters (OrdAlias is a varchar, and AliasSourceCode is a tinyInt)After all this - then, this code runsAny ideas why I'm getting this error??
View 1 Replies
View Related
Dec 16, 1999
all schedulled task on server failed for 18450 Process Exit Code 1. ...t Utility, Version 6.50.240 Copyright (C) Microsoft Corporation, 1995 - 1996 [Microsoft SQL-DMO] Error 18450: [SQL Server] Login failed- User: sqlexec Reason: Not defined as a valid user of a trusted SQL Server connection.
Any information on how to solve it
View 1 Replies
View Related
Nov 30, 2006
Code:
objrs.Open "Select * from [klcc_f$]", objConn, adOpenStatic
why IM getting dollar sign is not a valid name ?
View 2 Replies
View Related
Feb 7, 2008
I wonder about whether this rule is valid or invalid for nested BEGIN/END statement...
Code:
BEGIN
BEGIN
--Query #1 (blah)...
END
WHILE EXISTS (SELECT TOP 1 * FROM #tmpTblPurchaseRaw)
BEGIN
BEGIN
--Query #2 (blah)...
END
BEGIN
--Query #3 (blah)...
END
END
END
I have no idea if nested BEGIN/END is allowed or not...
View 1 Replies
View Related
Mar 17, 2004
I've got a linked server setup to DB2, and some of the
date fields in the DB contain 1/1/0001 values.
I've got views created in SQL2000 against the DB2 linked server.
When I run a query against a particular table that contains multiple field of datetime type.
I get the below error
Server: Msg 8114, Level 16, State 8, Line 1
Error converting data type DBTYPE_DBTIMESTAMP to datetime.
This only happens when I include in the select the field that contains 1/1/0001 values.
I assume since valid dates ranges in SQL are from
January 1, 1753 through December 31, 9999, this would be
what's causing this.
I tried to covert in the select but that failed as well. The only thing that I've been able to do, is to use a DTS to pull the data from the DB2 to a local SQL2000 table, with that fields type set as varchar. This works.
Using a DTS to pull the data to a local table in production isn't a viable workaround, since this table contains 1.8 million rows.
How is DTS converting this field, when convert fails in the select?
How do I get around this?
Thanks
View 13 Replies
View Related
Jan 28, 2008
Hi folks
I've just set up a maintenance plan that backs up all user databases daily and logs hourly. I've just noticed that the plan history is giving the following error -
Database 'BizTalkEDIDb' is not valid to be included in the maintenance plan.
Has anyone seen this before or know how to resolve it?
James
View 8 Replies
View Related
Nov 13, 2006
New to SQL Server installations. I downloaded the SQL Server Express with Advanced; when I double click the Setup.exe, I get a pop-up "document path/file is not a valid Win32 application". I upgraded from XP Home to XP Pro SP2.0. Any suggestions?
View 1 Replies
View Related
Feb 12, 2008
Hello Everybody
I'm getting a strange error.
I have created a Datatable and in this table I have multiple Columns.
I have given them all a name and now when I want to put data in the DataTable I get a error.
All goes well until I try to Update the Datatable
Code Snippet
DataRow DrWb = ppcDbDataSet.Item.NewRow();
DrWerkbon["ItemNummer"] = Defines.mcItem.miItemNr;
DrWerkbon["WorkerNummer"] = Defines.mcWorker.msWorkerNr;
Defines.mcItem.msWorkerNr = Defines.mcWorker.msWorkerNr;
DrWerkbon["CustomNummer"] = Defines.mcCustom.msCustomNr;
Defines.mcItem.msCustomNr = Defines.mcCustom.msCustomNr;
DrWerkbon["WbRedenBezoek"] = edRedenBezoek.Text;
Defines.mcItem.msReason = DrWb["WbReason"].ToString();
ppcDbDataSet.Item.Rows.Add(DrWerkbon);
ItemTableAdapter.Update(DrWb);
ppsDbDataSet.Clear();
ItemTableAdapter.Fill(ppcDbDataSet.Item);
At the ItemTableAdapter.Update(DrWb) it gives the error:
SqlCeException was unhandled
The Column name is not valid. [ Node name (if any) = , Column name = WbReason ]
I don't understand why it is giving this error because the name of the column realy is WbReason
Does anybody know what to do about this??
Kind regards
Korsten
View 3 Replies
View Related
Oct 4, 2007
Hi,
I'm trying to set up a data-driven subscription and having problems with parameters. On the Report Parameter Values screen of the Create Data-Driven Subscription function I have set a parameter TimesheetPeriodEnd to "Specify a static value" and checked the NULL box. In the report the parameter is type string and allows nulls. When I try to run the subscription the reports are not sent and the error log contains the following message:
ReportingServicesService!library!f!10/05/2007-09:31:08:: Status: Failure sending mail: Default value or value provided for the report parameter 'TimesheetPeriodEnd' is not a valid value.
ReportingServicesService!notification!f!10/05/2007-09:31:08:: Notification 0ae544df-4b1b-4a46-b7ab-cdefdca201be completed. Success: False, Status: Failure sending mail: Default value or value provided for the report parameter 'TimesheetPeriodEnd' is not a valid value., DeliveryExtension: Report Server Email, Report: Timesheet, Attempt 0
I am also setting other parameters for this subscription in the same way and not getting errors.
Any ideas? Previously I have had problems passing null values to parameters from the subscription query "Get value from database" from SELECT NULL AS ParameterName (this function just doesn't seem to work in SSRS). But I'm surprised I can't even seem to get this working with the default settings.
Regards,
Greg
View 5 Replies
View Related
Jan 17, 2006
I pass in a variable SourceServer to my package via the command line. In our production environment we are seeing:
The expression "@[User::SourceServer]" on property "ServerName" cannot be evaluated. Modify the expression to be valid
Is this just because the evaluation takes place prior to the command line parameters being set and I need to turn off validation?
Thanks,
Chris
View 2 Replies
View Related
Sep 26, 2007
I am deploying an rdl that is being deployed in a server.But i am encountering a problem regarding the valid values of the parameter.My parameters have dependencies,and one of my parameter comes out with two dependencies.
Scenario :
User needs to input his userID to access Book A.
Book B needs Book A because the output will be depending on the its content.
And Book C depend on Book B.
Problem:
when deploying, only Book A will have the initial value.The dependency in Book B is only one,which is fine.It shows its valid values. But how about for Book C which have 2 dependencies? Because it doesnt show it's valid values..
View 3 Replies
View Related
Jan 28, 2008
The configuration file name "C:......XMLSSIS2005_ConStr.dtsConfig" is not valid. Check the configuration file name.
The path is correct but we got this error. Please help us.
View 1 Replies
View Related
Jun 12, 2015
when installing sql server error showing file format is not vaild
View 3 Replies
View Related
May 3, 2006
I have just downloaded the MS SQL Server Management Studio Express, and are following a tutorial on www.learnvisualstudio.net
Now I am having trouble with some owner information. The message says :
"Database diagram support objects cannot be installed because this database does not have a valid owner. To continue, first use the Files page of the Database Properties dialog box or the ALTER AUTORIZATION statement to set the database owner to a valid login, then add the database diagram support objects"
I should mention that my WIN XP username is "Bjørn" with the Norwegian letter "Ø" in the middle. I suspect it to have a problem with that letter?
Any better suggestions?
View 5 Replies
View Related
May 28, 2007
Hi there guys!!
I am having an issue with generating a table for an report on the fly. I have been referring to the example on www.gotreportviewer.com and their example works fine but when i attempt to do my own version (by adding the table, I get the following error:
The report definition is not valid. Details: The element 'TableColumns' in namespace 'http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition' has incomplete content.
List of possible elements expected: 'http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition:TableColumn'.
From my understanding 'TableColumns' was not expected even though i reference it correctly in my code and I it is defined in the ReportDefinition. It also causes no problems for the example from the above website.
Can anyone help with this problem?
Thanks a million!
View 3 Replies
View Related
Nov 14, 2006
Hey,
I'm new to this whole SQL Server 2005 thing as well as database design and I've read up on various ways I can integrate business constraints into my database. I'm not sure which way applies to me, but I could use a helping hand in the right direction.
A quick explanation of the various tables I'm dealing with:
WBS - the Work Breakdown Structure, for example: A - Widget 1, AA - Widget 1 Subsystem 1, and etc.
Impacts - the Risk or Opportunity impacts for the weights of a part/assembly. (See Assemblies have Impacts below)
Allocations - the review of the product in question, say Widget 1, in terms of various weight totals, including all parts. Example - September allocation, Initial Demo allocation, etc. Mostly used for weight history and trending
Parts - There are hundreds of Parts which will eventually lead to thousands. Each part has a WBS element. [Seems redundant, but parts are managed in-house, and WBS elements are cross-company and issued by the Government]
Parts have Allocations - For weight history and trending (see Allocations). Example, Nut 17 can have a September 1st allocation, a September 5th allocation, etc.
Assemblies - Parts are assemblies by themselves and can belong to multiple assemblies. Now, there can be multiple parts on a product, say, an unmanned ground vehicle (UGV), and so those parts can belong to a higher "assembly" [For example, there can be 3 Nut 17's (lower assembly) on Widget 1 Subsystem 2 (higher assembly) and 4 more on Widget 1 Subsystem 5, etc.]. What I'm concerned about is ensuring that the weight roll-ups are accurate for all of the assemblies.
Assemblies have Impacts - There is a risk and opportunity impact setup modeled into this design to allow for a risk or opportunity to be marked on a per-assembly level. That's all this table represents.
A part is allocated a weight and then assigned to an assembly. The Assemblies table holds this hierarchical information - the lower assembly and the higher one, both of which are Parts entries in the [Parts have Allocations] table.
Therefore, to ensure proper weight roll ups in the [Parts have Allocations] table on a per part-basis, I would like to check for any inserts, updates, deletes on both the [Parts have Allocations] table as well as the [Assemblies] table and then re-calculate the weight roll up for every assembly. Now, I'm not sure if this is a huge performance hog, but I do need to keep all the information as up-to-date and as accurate as possible. As such, I'm not sure which method is even correct, although it seems an AFTER DML trigger is in order (from what I've gathered thus far). Keep in mind, this trigger needs to go through and check every WBS or Part and then go through and check all of it's associated assemblies and then ensure the weights are correct by re-summing the weights listed.
If you need the design or create script (table layout), please let me know.
Thanks.
View 4 Replies
View Related
Jul 20, 2005
Are there any limitations or gotchas to updating the same table whichfired a trigger from within the trigger?Some example code below. Hmmm.... This example seems to be workingfine so it must be something with my specific schema/code. We'reworking on running a SQL trace but if anybody has any input, fireaway.Thanks!create table x(Id int,Account varchar(25),Info int)GOinsert into x values ( 1, 'Smith', 15);insert into x values ( 2, 'SmithX', 25);/* Update trigger tu_x for table x */create trigger tu_xon xfor updateasbegindeclare @TriggerRowCount intset @TriggerRowCount = @@ROWCOUNTif ( @TriggerRowCount = 0 )returnif ( @TriggerRowCount > 1 )beginraiserror( 'tu_x: @@ROWCOUNT[%d] Trigger does not handle @@ROWCOUNT[color=blue]> 1 !', 17, 127, @TriggerRowCount) with seterror, nowait[/color]returnendupdate xsetAccount = left( i.Account, 24) + 'X',Info = i.Infofrom deleted, inserted iwhere x.Account = left( deleted.Account, 24) + 'X'endupdate x set Account = 'Blair', Info = 999 where Account = 'Smith'
View 1 Replies
View Related
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