What Code Is Required To Use The Trigger With The Application Of .NET && SQL 2005
Apr 22, 2007
Hi Everyone,
I m using ASP.NET 2005 with C# and SQL SERVER 2005.
I m using stored procedure and sql datasource control to retrieve the data.
I want to use the trigger alongwith storedprocedure.
I have created the following trigger on emp_table.
CREATE TRIGGER Employeee on emp_table
AFTER DELETE AS
DECLARE @empid int
SELECT @empid=empid from emp_table where locationid=(SELECT locationid from deleted)
IF @@ROWCOUNT=0
DELETE FROM location_table where locationid=(SELECT locationid from deleted)
What i wanted to know is how can i use it with asp.net and sql server 2005 when any
update,delete or insert query is executed thru the stoed procedure...
What code is required to use the trigger with the application of .NET
thanxs.....
View 2 Replies
ADVERTISEMENT
Dec 21, 2007
Hi I am trying to inset data to my sql 2005 database using a webform.. the code I have is
3 <asp:SqlDataSource ID="SqlDataSource1" runat="server" 4 5 ConnectionString="<%$ ConnectionStrings:SQL2005440975 %>" 6 7 InsertCommand="INSERT INTO [dbo.asp.net_Addresstbl] ([Salutation], [fname], [sname], [Daydb], [Monthdb], [Yeardb], [txtOrg], [txtLine1], [txtLine2], [txtLine3], [txtTown], [txtPostcode], [UserID]) 8 9 VALUES (@Salutation, @fname, @sname, @Daydb, @Monthdb, @Yeardb, @txtOrg, @txtLine1, @txtLine2, @txtLine3, @txtTown, @txtPostcode, @UserID)" 10 11 <InsertParameters>12 <asp:FormParameter FormField="Salutation" Name="Salutation" Type="String" />13 <asp:FormParameter FormField="fname" Name="fname" Type="String" />14 <asp:FormParameter FormField="sname" Name="sname" Type="String" />15 <asp:FormParameter FormField="Daydb" Name="Daydb" Type="Decimal" />16 <asp:FormParameter FormField="Monthdb" Name="Monthdb" Type="String" />17 <asp:FormParameter FormField="Yeardb" Name="Yeardb" Type="Decimal" />18 <asp:FormParameter FormField="txtOrg"Name="txtOrg" Type="String" />19 <asp:FormParameter FormField="txtLine1" Name="txtLine1" Type="String" />20 <asp:FormParameter FormField="txtLine2" Name="txtLine2" Type="String" />21 <asp:FormParameter FormField="txtLine3" Name="txtLine3" Type="String" />22 <asp:FormParameter FormField="txtTown" Name="txtTown" Type="String" />23 <asp:FormParameter FormField="txtPostcode"Name="txtPostcode" Type="String" />24 <asp:FormParameter FormField="UserID" Name="UserID" Type="Object" />25 </InsertParameters>26 </asp:SqlDataSource>27 28 <asp:DropDownList ID="Salutation" runat="server" ValidationGroup="Address">29 <asp:ListItem>Choose One</asp:ListItem>30 <asp:ListItem>Mr.</asp:ListItem>31 <asp:ListItem>Mrs.</asp:ListItem>32 <asp:ListItem>Ms.</asp:ListItem>33 <asp:ListItem>Miss.</asp:ListItem>34 <asp:ListItem>Rev.</asp:ListItem>35 <asp:ListItem>Doc.</asp:ListItem>36 <asp:ListItem>Other.</asp:ListItem>37 </asp:DropDownList>38 39 <asp:TextBox ID="fname" runat="server" CausesValidation="True"></asp:TextBox>40 41 <asp:TextBox ID="sname" runat="server" CausesValidation="True"></asp:TextBox>42 43 <asp:DropDownList ID="Daydb" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">44 <asp:ListItem>Day</asp:ListItem>45 <asp:ListItem>01</asp:ListItem>46 <asp:ListItem>02</asp:ListItem>47 <asp:ListItem>03</asp:ListItem>48 <asp:ListItem>04</asp:ListItem>49 <asp:ListItem>05</asp:ListItem>50 <asp:ListItem>06</asp:ListItem>51 <asp:ListItem>07</asp:ListItem>52 <asp:ListItem>08</asp:ListItem>53 <asp:ListItem>09</asp:ListItem>54 <asp:ListItem>10</asp:ListItem>55 <asp:ListItem>11</asp:ListItem>56 <asp:ListItem>12</asp:ListItem>57 <asp:ListItem>13</asp:ListItem>58 <asp:ListItem>14</asp:ListItem>59 <asp:ListItem>15</asp:ListItem>60 <asp:ListItem>16</asp:ListItem>61 <asp:ListItem>17</asp:ListItem>62 <asp:ListItem>18</asp:ListItem>63 <asp:ListItem>19</asp:ListItem>64 <asp:ListItem>20</asp:ListItem>65 <asp:ListItem>21</asp:ListItem>66 <asp:ListItem>22</asp:ListItem>67 <asp:ListItem>23</asp:ListItem>68 <asp:ListItem>24</asp:ListItem>69 <asp:ListItem>25</asp:ListItem>70 <asp:ListItem>26</asp:ListItem>71 <asp:ListItem>27</asp:ListItem>72 <asp:ListItem>28</asp:ListItem>73 <asp:ListItem>29</asp:ListItem>74 <asp:ListItem>30</asp:ListItem>75 <asp:ListItem>31</asp:ListItem>76 </asp:DropDownList>77 78 <asp:DropDownList ID="Monthdb" runat="server" style="text-align: left">79 <asp:ListItem>Month</asp:ListItem>80 <asp:ListItem>January</asp:ListItem>81 <asp:ListItem>February</asp:ListItem>82 <asp:ListItem>March</asp:ListItem>83 <asp:ListItem>April</asp:ListItem>84 <asp:ListItem>May</asp:ListItem>85 <asp:ListItem>June</asp:ListItem>86 <asp:ListItem>July</asp:ListItem>87 <asp:ListItem>August</asp:ListItem>88 <asp:ListItem>September</asp:ListItem>89 <asp:ListItem>October</asp:ListItem>90 <asp:ListItem>November</asp:ListItem>91 <asp:ListItem Value="12">December</asp:ListItem>92 </asp:DropDownList>93 94 <asp:DropDownList ID="Yeardb" runat="server" style="text-align: left" 95 OnSelectedIndexChanged="Year_SelectedIndexChanged" 96 DataSourceID="YearDataSource" DataTextField="Year" DataValueField="Year">97 <asp:ListItem Selected="True">Choose Year..</asp:ListItem>98 </asp:DropDownList>99 <asp:AccessDataSource ID="YearDataSource" runat="server" 100 DataFile="~/App_Data/year.mdb" SelectCommand="SELECT [Year] FROM [Year]">101 </asp:AccessDataSource>102 103 <asp:TextBox ID="txtFind" runat="server" CausesValidation="True" ValidationGroup="address"></asp:TextBox>104 105 <asp:Button ID="btnFind" runat="server" Text="Find" 106 OnClick="btnFind_Click" ValidationGroup="address" 107 OnClientClick="lstProperties" />108 109 110 <asp:ListBox ID="lstProperties" runat="server" AutoPostBack="True" 111 OnSelectedIndexChanged="lstProperties_SelectedIndexChanged" Visible="False" 112 Width="200px"></asp:ListBox>113 114 <asp:TextBox ID="txtOrg" runat="server" OnTextChanged="txtOrg_TextChanged" 115 ReadOnly="True" ValidationGroup="address2" Visible="False"></asp:TextBox>116 117 <asp:TextBox ID="txtLine1" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>118 119 <asp:TextBox ID="txtLine2" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>120 121 <asp:TextBox ID="txtLine3" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>122 123 <asp:TextBox ID="txtTown" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>124 125 <asp:TextBox ID="txtPostcode" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>126 127 <asp:Label ID="lblAddress" runat="server" CssClass="style9"></asp:Label>128 129 <asp:Button ID="submitaddress" runat="server" Text="Add Details" 130 style="text-align: centre" CommandName="Submit" 131 ValidationGroup="address" PostBackUrl="~/MemberPages/account.aspx" />132 133 </asp:Content>
Will this code work? if not can you explain why not and offer an example that will work. In the mean time I am reading up on these insert statements.
Regards
Mal
View 5 Replies
View Related
Dec 13, 2007
My web project (ASP.NET 2.0 / C#) runs against sql server 2000 and uses the System.Data.SqlClient.using System.Data.SqlClient;
I use System.Data.SqlClient.SqlConnection and System.Data.SqlClient.SqlCommand to make the connections to the database and do selects and updates. Is it correct to continue to use these against SQL Server 2005? I ask because I made a connection string (outside of .Net) for SqlServer 2005 using the SQL native provider and it had the following - Provider=SQLNCLI.1 and any connection strings I had made (also outside of ASP.NET) fro SQL Server all used Provider=SQLOLEDB.1. This is why I wondered if there is a different SqlClient in .Net 2.0 for SQL Server 2005?
Cheers
Al
View 1 Replies
View Related
Nov 20, 2007
I understand the general SQL no-multiplexing-to-reduce-CALs idea. I have a semi-edge case: Does this apply to applications like IIS when using SQL to log access? IIS allows you to log web hits to an ODBC database -- so for a typical web app, that would mean getting a CPU license for SQL server. Is that correct?
What about a network monitoring app that sniffs packets and records network statistics? If there's only a 2 network devices (but potentially packets from millions of users), what does licensing look like then?
When does the "manual step" allowance kick in? For instance, if a user generates a report from SQL server and it's automatically saved as an HTML file to a webserver thats accessed publicly -- what's licensing for that?
Is a CPU license needed in all these cases?
-Michael
View 4 Replies
View Related
Jul 26, 2006
I am writting a very simple ASP.NET code, I am simlply trying to
establish a connection with the database in SQL Server 2000 and than
closing the connection but still I am getting an exception,the name of
the database is mydatabase, SQL Server 2000 is running in the windows
authenticationfiltered=SSPI. The name of SQL Server 2000 running
onfiltered=xyz,
I checked the name from SQL Server Service Manager.Also I would like to
state here that I also tryed to establish a connection using C# and the
connection was successfully establish which means that there is no
problem with SQL Server also I sucessfully established the connection
with MS Access and my ASP.NET application which proves that there is no
problem with IIS also.Also please check that the connection string
which I am providing is correct or not.The exception which I am getting
is as follows:
///////////////////////////////////////////////////////////////////////////////
An exception occured while establishing connection
Login failed for user 'xyzASPNET'.
////////////////////////////////////////////////////////////////////////////
Please also note that I have a user with the name xyz/Administrator in
the logins of Sql Server 2000. Also note one more thing that the name
of my PC is xyz, I think that there is some problem with the connection
string which i am providing so please especially check the connection
string that either I have missed some thing or some thing has gone
wrong,also please tell that are there any security restructions for
ASP.NET to access SQL Server 2000 or some thing like that which I have
to remove.The code is as follows:
//////////////////////////////////////////////////////////////////////////////////////
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
void Page_Load(Object sender , EventArgs e)
{
try
{
SqlConfiltered=new SqlConnection("server=xyz;Integrated Security=SSPI;database=mydatabase;");
connection.Open();
Response.Write("<b>Connection is successfully established</b>");
connection.Close();
}
catch(Exception ex)
{
Response.Write("<b>An exception occured while establishing connection</b><br>"+" "+ex.Message.ToString());
}
}
</Script>
The same above code is also present in the attachement file data.aspx ,
please guide me where I am making mistake and please tell me that how
can I correct this mistake so that the code executes correctly.Also
please tell that what things should be included in the connection
string and also please check the connection string of this code.
View 1 Replies
View Related
Feb 18, 2004
A Source code required for create SQL Server Database,Tables,Procedures programatically
View 1 Replies
View Related
May 21, 2008
hi,
Where can I get the Complete code/URL/ Good BOOK for the Print,Print Priview for the CV++ "multipage printing" concept.
thanks
murthy
View 2 Replies
View Related
Aug 5, 2007
Hi,
I have tables parent - PurchaseInvoices and child - PurchaseInvoiceDetails. I have trigger in PurchaseInvoiceDetails that would update stock qty based on Location code stored in parent table - PurchaseInvoices upon INSERT/UPDATE/DELETE.
I also set table RI to have cascade delete. I faced problem that, when I delete record in parent table, it would cascade delete child table. Trigger in child table fired and try to update stock qty. However, in this case, trigger unable to locate parent table record anymore.
How to overcome this? I can't move my stock update code to other place since I got to update stock if any changes happen to child table.
Please advice.
View 7 Replies
View Related
Nov 28, 2006
Hi,
I am developing an application that uses Access database (mdb file) to store the user data. The user of this application is not interested in the database file (to view in MS Access Environment). Does the user machine requires MS Access installation to run my application or just some couple of dlls (OleDB driver, Access DB Engine,..) should be enough to run my application?
Thanks,
Rao
View 3 Replies
View Related
Apr 10, 2008
Hi,
Any one tell me the code to connect to .sdf file in c# windows application?And tell the requirments to conncet.My sdf file path is this
C:\Documents and Settings\koti\My Documents\Example.sdf
I write this code.It is not working
string str = "Provider=Microsoft.SQLSERVER.MOBILE.OLEDB.3.0;Data Source=C:\Documents and Settings\koti\My Documents\Example.sdf;SSCE:Encrypt Database=True";
SqlCeConnection cn = new SqlCeConnection(str);
cn.Open();
Ant one help me Plz...
Regards,
venkat.
View 6 Replies
View Related
Jun 17, 2005
I am newbie to DTS stuff. Is there anyway I can trigger DTS package thr' asp.net applicationPlease help
View 1 Replies
View Related
Aug 10, 2007
Hi all,
I have a VB.NET 2005 application that needs to monitor constantly each change of a field on a SQL server 2005.
Is there a way of setting a trigger up in the SQL Server that notifies the VB.NET application to avoid having the VB.NET apllication querying the SQL table all day for changes?
The table in SQL stores a temperature value. I need the VB.NET application to receive this value everytime there's a change. I could do a timer on the VB.NET application to check for changes in the table every 1 second but I don't think this is efficient. The temperature value may change once every two or three seconds.
The VB.NET application will process the temperature value.
Is there a way of notifying the VB.NET application (which runs from a different server) from within SQL Server? If so, how? If not, what would you go about implementing this?
Thanks again for your comments,
ST
View 1 Replies
View Related
Apr 30, 2008
Is it possible to get a variable( for example user id of the currently logged in user) in a CLR SQL Server trigger.
View 1 Replies
View Related
Jul 27, 2006
Hi all--I'm trying to convert a function which I inherited from a SQL Server 2000 DTS package to something usable in an SSIS package in SQL Server 2005. Given the original code here:
Function Main()
on error resume next
dim cn, i, rs, sSQL
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"
set rs = CreateObject("ADODB.Recordset")
set rs = DTSGlobalVariables("SQLstring").value
for i = 1 to rs.RecordCount
sSQL = rs.Fields(0).value
cn.Execute sSQL, , 128 'adExecuteNoRecords option for faster execution
rs.MoveNext
Next
Main = DTSTaskExecResult_Success
End Function
This code was originally programmed in the SQL Server ActiveX Task type in a DTS package designed to take an open-ended number of SQL statements generated by another task as input, then execute each SQL statement sequentially. Upon this code's success, move on to the next step. (Of course, there was no additional documentation with this code. :-)
Based on other postings, I attempted to push this code into a Visual Studio BI 2005 Script Task with the following change:
public Sub Main()
...
Dts.TaskResult = Dts.Results.Success
End Class
I get the following error when I attempt to compile this:
Error 30209: Option Strict On requires all variable declarations to have an 'As' clause.
I am new to Visual Basic, so I'm on a learning curve here. From what I know of this script:
- The variables here violate the new Option Strict On requirement in VS 2005 to declare what type of object your variable is supposed to use.
- I need to explicitly declare each object, unless I turn off the Option Strict On (which didn't seem recommended, based on what I read).
Given this statement:
dim cn, i, rs, sSQL
I'm looking at "i" as type Integer; rs and sSQL are open-ended arrays, but can't quite figure out how to read the code here:
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"
set rs = CreateObject("ADODB.Recordset")
This code seems to create an instance of a COM component, then pass provider information and create the recordset being passed in by the previous task, but am not sure whether this syntax is correct for VS 2005 or what data type declaration to make here. Any ideas/help on how to rewrite this code would be greatly appreciated!
View 7 Replies
View Related
Apr 30, 2001
I have a trigger on a table which when I do a direct update to throught QA seems to work fine. When a user developed application updates the record it locks their screen and record. I can't see where it could be causing it, but I am pasting it below. Any thoughts/comments greatly appreciated
CREATE TRIGGER tr_Patient_Updt2
ON patient_
FOR UPDATE
AS
if update(df_last_cholestero)
begin
declare @tstyears int
declare @tdate datetime
declare @sdate datetime
declare @bdate datetime
declare @ptage int
declare @actid varchar(12)
select @bdate = convert(datetime,df_last_cholestero,101), @actid = account_id
from inserted
select @ptage = dbo.GetAge(convert(datetime,patient.Date_Of_Birth, 101), GETDATE())
from patient where patient.account_id = @actid
select @sdate = convert(datetime,patient.Date_Of_Birth,101)
from patient where patient.account_id = @actid
select @tstyears = datediff(month,@bdate,getdate())
if @ptage between 18 and 65
begin transaction
begin
if @tstyears < 12
begin
set @ptage = @ptage + 5
set @sdate = DATEADD(year, @ptage, @sdate)
update patient_
set df_next_cholestero = convert(char(08),@sdate,112)
where patient_.account_id = @actid
end
else if @tstyears >= 12 and @tstyears < 24
begin
set @ptage = @ptage + 4
set @sdate = DATEADD(year, @ptage, @sdate)
update patient_
set df_next_cholestero = convert(char(08),@sdate,112)
where patient_.account_id = @actid
end
else if @tstyears >= 24 and @tstyears < 36
begin
set @ptage = @ptage + 3
set @sdate = DATEADD(year, @ptage, @sdate)
update patient_
set df_next_cholestero = convert(char(08),@sdate,112)
where patient_.account_id = @actid
end
else if @tstyears >= 36 and @tstyears < 48
begin
set @ptage = @ptage + 2
set @sdate = DATEADD(year, @ptage, @sdate)
update patient_
set df_next_cholestero = convert(char(08),@sdate,112)
where patient_.account_id = @actid
end
if @tstyears > 48
begin
set @ptage = @ptage + 1
set @sdate = DATEADD(year, @ptage, @sdate)
update patient_
set df_next_cholestero = convert(char(08),@sdate,112)
where patient_.account_id = @actid
end
end
end
commit transaction
View 1 Replies
View Related
Apr 28, 2008
I'm updating a process that recreates a large table every night. The table is the result of a bunch of nightly batch processes and holds a couple million records. In the past, each night at the end of the batch jobs the table would be dropped and re-created with the new data. This process was embodied in dynamic sql statements from an MFC C++ program, and my task is to move it to a SQL Server 2000 stored procedure that will be called from a .Net app. Here's the relevant code from my procedure:
sql Code:
Original
- sql Code
-- recreate new empty BatchTable table
print 'Dropping old BatchTable table...'
exec DropBatchTable --stored procedure called from old code that does a little extra work when dropping the table
-- validate drop
If exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BatchTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
Begin
RAISERROR( 'Unable to drop old BatchTable!',0,1) WITH NOWAIT
End Else Begin
print 'Old BatchTable dropped.'
End
print 'Creating new BatchTable...'
SELECT TOP 0 *, cast('' as char(3)) as Client, cast('' as char(12)) as ClientDB
INTO dbo.BatchTable
FROM differentDB.dbo.BatchArchives
--validate create
If Not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BatchTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
Begin
RAISERROR( 'Unable to create new BatchTable!',0,1) WITH NOWAIT
End Else Begin
print 'New BatchTable Created.'
End
-- recreate new empty BatchTable table print 'Dropping old BatchTable table...' exec DropBatchTable --stored procedure called from old code that does a little extra work when dropping the table -- validate drop IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[BatchTable]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN RAISERROR( 'Unable to drop old BatchTable!',0,1) WITH NOWAIT END ELSE BEGIN print 'Old BatchTable dropped.' END print 'Creating new BatchTable...' SELECT TOP 0 *, CAST('' AS CHAR(3)) AS Client, CAST('' AS CHAR(12)) AS ClientDB INTO dbo.BatchTable FROM differentDB.dbo.BatchArchives --validate create IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[BatchTable]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN RAISERROR( 'Unable to create new BatchTable!',0,1) WITH NOWAIT END ELSE BEGIN print 'New BatchTable Created.' END
The print statements are there because the .net app will read them in and then write them to a log file. Some of the other mechanics are there to mimic the old process. The idea is to duplicate the old process first and then work on other improvements.
This works in Management studio. The .Net App reports that the old table was dropped, but when it tries to create the new table it complains that "There is already an object named 'BatchTable' in the database." I have verified that the old table is removed.
Any ideas on how to fix this?
View 4 Replies
View Related
Jul 14, 2006
I have table T1 and I am trying to extract some date from T1 table based on inserts, updates and deletes. The destination table T2 has three fields F1, F2, F3, so I need something like
Insert into T2 (F1, F2, F3)
Select (F1, F2,Type)
From T1
Type should be defined based on Insert, Update, or Delete. This will be my first trigger, Can anyone write this trigger for me?
View 1 Replies
View Related
Jun 14, 2008
How can I write a trigger for the below issue,
I have table named Subscribers with fields Name (varchar), MobileNumber (varchar), status (char). Here if I want to insert a record into this table then first I need to check whether this mobile number exist or not in this table. If it is not exist then this record should be insert and if it is exist then this record should not be insert in to this table.
How can I do a trigger for this one?
with regards
Shaji
View 5 Replies
View Related
Aug 26, 2007
CREATE TRIGGER tr_1
ON Users
FOR UPDATE OF u_paid
AS
BEGIN
..........
END
any idea what is wrong with the above code?
The users table exist and u_paid is a column in that table.
Im getting the following error:
Incorrect syntax near the keyword 'OF'.
View 18 Replies
View Related
Jul 20, 2005
Am using SQL Server 2000 on WINXP Pro. Have a requirement to change someOracle triggers to SQL 2000. I have modied this one Insert Trigger, but getan error when I attempt to compile:CREATE TRIGGER trg_ins_attend_audit_logON ATTENDAFTER INSERT-- Insert Trigger for SQL ServerASDECLAREBEGINInsert ATTEND_AUDIT_LOGSelect licnum,lic_suffix,als_hsp_id,last_name,first_name,mid_name,birth_date,sex,serv1,serv2,serv3,paid_vol,amb_res,street1,street2,town,state,zipcode,phone,lic_year,print_lic,lic_exp,send_hx,user_id,getdate(),"I",modifiedfrom insertedENDERROR:Incorrect syntax near "AS."Can anyone point out the error of my ways here??
View 2 Replies
View Related
Jul 14, 2006
I have table T1 and I am trying to extract some date from T1 table based on inserts, updates and deletes. The destination table T2 has three fields F1, F2, F3, so I need something like
Insert into T2 (F1, F2, F3)
Select (F1, F2,Type)
From T1
Type should be defined based on Insert, Update, or Delete. This will be my first trigger, Can anyone write this trigger for me?
View 5 Replies
View Related
Jun 4, 2007
Hello all
I've been thrown in at the deep end by the manager and asked to use a SQL database for a new site. I've managed to get most of the code working but are having trouble with this particular one.
The idea is that a user can log a fault (online) and that this gets added to a table. Once the data is added a trigger fires that takes this new data and loops through an "e-mail alert" table containing settings for different department managers and then stores the relevant manager name in a separate table (e-mail sent fromt this table to the manager) once the department and fault id's match.
I have the following code (which is by no means good) in my trigger - did I says this is my first outing into SQL land!!ALTER TRIGGER [dbo].[usd_emailalertqueue]
ON [dbo].[FaultPostings] AFTER INSERT
AS
-- declare variables from new fault table
DECLARE @iDeptID intDECLARE @iFaultID intDECLARE @iReferenceID int
-- declare variables from email alerts tableDECLARE @Managername nvarchar(255)DECLARE @DeptID intDECLARE @FaultID intDECLARE @ReferenceID int
-- Read in values new fault tableSELECT @sParam = FaultDescription FROM INSERTEDSELECT @iFaultID = FaultID FROM INSERTEDSELECT @iDeptID = DeptID FROM INSERTEDSELECT @iReferenceID = ReferenceID FROM INSERTED
BEGIN
-- Read values from saved e-alertsSELECT @Managername = Managername FROM [dbo].[emailAlerts]SELECT @DeptID = DeptID FROM [dbo].[emailAlerts]SELECT @FaultID = FaultID FROM [dbo].[emailAlerts]
INSERT INTO EmailAlertQueue(ReferenceID,Managername)SELECT @iReferenceID, @Managername
FROM [dbo].[emailAlerts] WHERE (@iDeptID = @Deptid) AND (@iFaultID = @Faultid) then END
At the moment, this is what happens when a fault is added: the EmailAlertQueue table gets populated with the name of the last managername from the emailAlerts table several times (only if the Dept and Fault id's macth otherwise nothing gets populated.. e.g. if there at 4 alerts setup in the EmailAlerts table with different dept and fault ID's but the last one matches the criteria the emailAlerts table is uotaed with 4 rows containing the managername. (Hope this makes sense).
I think I need to have some sort of loop but so far as I can tell a "For Each" loop doesn't work in triggers (i could be wrong though).
(I'm not even sure if this is the correct approach to take)
As usual, any help is appreciated.
Thanks
Chooch
View 3 Replies
View Related
Mar 11, 2005
Does anyone have code for a trigger that when the user deletes the record trigger it to insert into another table? Thanks in advance and appreciate your help!
View 4 Replies
View Related
Apr 21, 2006
Hi.
I am trying to get the schema in which the trigger is created within the CLR code.
1)create a new schema MySchema.
2) created a table MySchema.MyTable
3) created the assembly and trigger ( create trigger MySchema.MyTrigger on MySchema.MyTable..... ) Trigger writes to another table MySchema.MyLog.
Code works fine if I hardcode Myschema.MyLog in the CLR but fails when I say just MyLog.
So how do dynamically get the trigger's schema name ?
Thanks for your help.
Nach
View 1 Replies
View Related
Apr 3, 2008
Hi,
Please can anyone help me code the trigger below. I have had errors pointing to "sp_configure 'SQL Mail XPs', 1;" and "RECONFIGURE", that this lines should be not where I have placed them. I have tried other combinations and have not worked at all! Is any other ways I can achieve this all?
Code Snippet
CREATE TRIGGER reminder
ON Bug_Report
FOR INSERT, UPDATE, DELETE
AS
sp_configure 'SQL Mail XPs', 1;
EXEC master..xp_sendmail 'MaryM',
'Don't forget to print a bug report.'
RECONFIGURE
View 3 Replies
View Related
Aug 24, 2007
Hi there,
Values in my database need to updated periodically. The code, upon starting the application, queries the database and stores the values in the Application collection. This is to avoid making a database call everytime the values are needed (increases performance). The drawback is that changes to the database values are not updated in the code.
How can I create a database trigger that will update the C# Application colllection whenever a table value is updated?
View 2 Replies
View Related
Aug 2, 2006
I would like to create a script that lists out all of the SQL code for the procedures and triggers I have created in a database.
What I want to do is save the code for each procedure/trigger as a *.SQL file without having to open up each one in Enterprise Manager and save them individually.
Listing the names is easy by looking in sysobjects, but is the SQL code stored in a system table anywhere?
Does anybody have any alternative approach to this problem?
Thanks in advance,
Mark
View 1 Replies
View Related
May 12, 2006
I have inherited a database and with it a set of triggers that are 'apparently' installed. However I have a number of different 'versions' for a specific update trigger and it is not clear from the files which is the latest, hence I am unsure of what 'version' of the trigger is installed in the database itself.
I am trying to retrieve the trigger code from the databse so that i can correctly determine which one of my trigger files is the latest version.
I don't want to end up in a situation where an earlier version of the update trigger is installed as this could wreck the underlying data.
I have tried using the syscomments.text column that relates to the trigger but it only gives me a concatenated version of the sql code and not enough to determine which file version was used for the trigger.
Is there a way of retreiving the entire SQL code that was entered rather than just the first few lines?
View 5 Replies
View Related
Jun 26, 2007
I've been searching for a bit but I can't seem to find a difinitive answer.
Can an SQL Server trigger call native C/C++ functions? If so, what is the mechanism?
Thanks in advance.
View 7 Replies
View Related
Oct 28, 2015
issues with triggers in Sql Server 2014.
A few weeks ago I've done a SQL Server migration from SQL Server 2000 to SQL Server 2014.It was a bit tricky but anything worked fine.
I have some legacy VB6 (Visual Basic 6) applications written in house which worked with Databases on the old SQL server 2000.Surprisingly, these applications worked well after the upgrade to SQL Server 2014 without having to change a piece of code.
Now, some users tell me that they receive some unusual message when saving data from these legacy applications.After investing for a few hours, I discovered that triggers are not executed when those users try to save data from grids or forms in their applications.Trying to reproduce the INSERT statement in SQL Server Management Studio, the triggers run well.From the application, they don't.
These applications connect to Database Server thru OLEDB connection with the following ADO connection string :
Provider=SQLOLEDB.1;Password={password};User ID={user};Initial Catalog={db};Data Source={datasource}.the {user} is a true SQL account who have read/write/delete access in the databases.
On the web there is a lot of questions involving the same issue, but only from SSIS.I found some articles about an OLEDB connection parameter named FastLoadOptions with a value of FIRE_TRIGGERS, but nowhere how to put it in the ADO OLEDB connection string.
how to reactivate the "normal" use of triggers from an ADO OLEDB connection ?Either with some obscur parameter in the connection string or options somewhere in the SQL Server 2014.
View 4 Replies
View Related
May 7, 2008
I have a database trigger that is set to call a CLR trigger/stored proc when a certain field in a table is updated. The issue is that if i execute the stored proc manually in enterprise studio, it works perfectly but the same call made through the trigger does not go through. A few more details -
I have CLR integration enabled on the sql server.
The dbo has UNSAFE ASSEMBLY rights
I have the both the assembly and the serialized dll imported in the database.
Here's the definition of the stored proc -
CREATE PROCEDURE [dbo].[WriteXMLNotification]
@TaskID [nvarchar](20)
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [DataInterfaceWebServices].[TaskUpdateXMLWriter.WriteXMLNotification].[run]
and the trigger -
CREATE TRIGGER [dbo].[tr_Task_U]
ON [dbo].[_Task]
FOR UPDATE, INSERT AS
IF UPDATE (TaskType_Status) OR UPDATE (TaskType) OR UPDATE (TaskType_SubType1)
BEGIN
SET NOCOUNT ON;
DECLARE @status AS INT
DECLARE @taskType AS INT
DECLARE @taskSubType AS INT
DECLARE @taskID as sysname
DECLARE @cmd as sysname
DECLARE @parentTask as sysname
DECLARE @NotificationXMLTaskID as sysname
SELECT @status = [TaskType_Status] FROM inserted
SELECT @taskType = [TaskType] FROM inserted
SELECT @taskSubType = [TaskType_SubType1] FROM inserted
SELECT @taskID = [TaskID] FROM inserted
SELECT @parentTask = [Parent_TaskID] FROM inserted
SELECT @NotificationXMLTaskID = [MCCTaskID] FROM _TaskNotificationXML WHERE [MCCTaskID] = @parentTask
IF (@status = 2602) AND (@taskType = 2282) AND (@taskSubType = 19500)
BEGIN
exec WriteXMLNotification @taskID;
END
ELSE IF (@taskType = 2285) AND (@parentTask IS NOT NULL) AND (@NotificationXMLTaskID IS NOT NULL)
BEGIN
exec WriteXMLNotification @parentTask;
END
END
I stepped into the trigger and it seems to execute the line " exec WriteXMLNotification @taskID;" but nothing happens, but if I run that same line manually, it works. Could it be that the impersonation by the EXECUTE AS clause is causing it to fail?
Please advise!
Thanks in Advance,
-Mihir Sonalkar.
View 1 Replies
View Related
Sep 6, 2007
My goal is to create a trigger to automatically set the value for a status id on a table based on set criteria. Depending on the values of other fields will determine the value that the status id field is assigned. So far, I have written the trigger to update the status id field and I go through a seperate Update statement for each status id value. The problem is that I can't get this to work at the record level. The problem that I am getting is that if I have 50 records in TABLE1 and at least one of them satisfies the where clause of the update statement, all of the records get updated. So, using these two update statements, all of my records end up with a status value of '24' because that was the last update statement run in the trigger. Here is the code I have so far:
CREATE TRIGGER dbo.JulieTrigger1
ON dbo.Table1
AFTER INSERT,UPDATE
AS
BEGIN
BEGIN TRY
/*Update Table1.Status to POTENTIAL (id 23) status */
UPDATE TABLE1
SET status_id = 23
WHERE EXISTS (SELECT *
FROM TABLE1 a INNER JOIN TABLE2 b
ON b.order_id = a.order_id
WHERE a.start_dt IS NULL
AND b.current_status_ind = 1
AND b.lead_status_id NOT IN (15,16)
AND a.order_id = TABLE1.order_id)
/*Update Table1.Status to ACTIVE (id 24) status */
UPDATE TABLE1
SET status_id = 24
WHERE EXISTS (SELECT *
FROM TABLE1 a
WHERE fill_ind = 1
AND (end_dt IS NULL OR end_dt > getdate() )
AND a.job_order_id = TABLE1.job_order_id)
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE()
IF @@TRANCOUNT > 0
ROLLBACK TRAN
-- Return the error to the calling object
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
)
END CATCH
SET NOCOUNT ON;
END
GO
Thanks in advance for any help!
-Julie
View 1 Replies
View Related
Aug 3, 2007
Hi there SQL Team
I hope I’ve posted this in the right section.
We have a customer, call them customerA
CustomerA has just employed a new Chief Information Officer.
The New CIO would like to make a few changes to the current way we have things right now.
Bare with me as I explain our environment.
We have The following Servers
Application Server[FSS (Dual DC Xeon 2.33GHz CPU, 4GB RAM, 3x72GB hdd RAID]
Database Server [FSS (Dual DC Xeon 2.33GHz CPU, 4GB RAM, 3x72GB hdd RAID)]
Both the above servers sit in a fully fault tolerant environment with daily backups power generators etc etc etc.1000MB network everything work 100%
Now my question:
The new CIO would like to move the DB server out of this environment to a remote building downtown, and have the application server connect to this remote db server.
Is this advisable?
What are the required connection speeds, so that the end user does not have to wait for a response?
What is the recommended response time IIS should give?
Please also note that we are in South Africa and broadband is VERY expensive / unreliable.
The CIO would like to install a 2Mbit radio link from this building to the ISP I’m not sure on the cost, but do know that this type of link is very unstable,
Their failover will be a 512kb fixed line or diginet line. Cost about ZAR 8000.00 per month
The application is extremely data / graphs intensive as it contain property information.
I think they average about 16000 visitors daily, not a lot.
If anyone can give me any input i would appreciated.
Thanks
View 1 Replies
View Related