Connection Level Variable For Trigger Use Possible?
May 19, 2008
I need to pass a application userid on every call to my database for triggers on the db to use.
I am connecting to my database using integrated security from my application, all on one windows domain account. However I need to get an application user id over on the connection for triggers to use to stamp in changelogs.
Currently everytime we open a connection we create a #table with the user id in it, but that is expensive, especially in our new SOA where connections are frequently created and dropped on requests.
Is there any way I can get a connection level variable over to the database server so triggers could read it?
I am doing a DB porting project in which i need to translate oracle specific queries to sql server.I need to convert following trigger to sqlserver specific .Any help will be appreciated
CREATE OR REPLACE TRIGGER T_BI_R_TARGET_OBJECTIVE BEFORE INSERT ON TARGET_OBJECTIVE REFERENCING OLD AS OLD NEW AS NEW FOR EACH ROW WHEN (NEW.TARGET_OBJECTIVE_ID IN (NULL,0)) DECLARE seq_id NUMBER; BEGIN SELECT TARGET_OBJECTIVE_ID_SEQ.NEXTVAL INTO seq_id FROM dual; :new.TARGET_OBJECTIVE_ID := seq_id; END;
Is there any row-level trigger available in SQL server(in oracle is does)
my problem is ..I am trying to write a trigger which updates all the items
But it give me error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.
My statement is : SET @var_item=(SELECT item_no FROM deleted)
How can i make it possible? Note: I am trying convert Oracle trigger to SQL Server trigger
I have a stored proc eg spProcA which does not start a transaction
If I call this proc from ado.net code without any transaction around it affecting the isolation level, the isolation level within the proc call is read committed, as expected
If I then call the same proc within a System.Transacstion.TransactionScope with a different isolation level eg Serializable, then i get the expected isolation level in the proc.
However, if i retry the proc without any transaction around it, the isolation level is now the same as the TransactionScope, (eg Serializable), and this persists until either the connection pool clears down (either because it becomes dormant or via an explicit ClearAllPools.
I can resolve this problem by setting the isolation level in every proc (or call to every proc), but i wondered if i am missing something more straight forward?
we are having an requirement to log the unauthorized backend update on database.Is there any other way ,apart from going and creating the triggers at each table to log the backend update.
Note :Is Database base level trigger is possible on SQL Server 2000?
hi actually i have a temporay table wich has four columns say col_1,col_2,col_3,col_4. so firstly i wud bulk insert from a text file wich mite contain thousands of rows. then from this temp table col_1 and col_2 shd go to master_a.wich has an identiy column as primary key. say id,col_1, col_2.
i will have another table detail_b where in there is a foreign key to the table master_a for id. so it will have f_id, col_3,col_4.
so i am riting a trigger on master_a. so whenver row is inserted in master_a. coresponding id and col 3 col4 shd be inserted into detail_b.
For this in oracle we have row level trigger. where in for each insertion in master a .. correspoding trigger will fire but in sql 2000.. but i wud like to implemtn row level trigger.. can u hlep me out..
Hi all in .net I've created an application that allows creation of triggers, i also want to allow the deletion of triggers. The trigger name is kept in a table, and apon deleting the record i want to use the field name to delete the trigger
I have the following Trigger
the error is at
DROP TRIGGER @DeleteTrigger
I'm guessing it dosen't like the trigger name being a variable instead of a static name how do i get around this?
hello guysi am using a table that its secondary key connected to its primary key...and as sql server 2000 doesnt allow cascade delete fore such,i had to write a trigger myselfso i wrote the following triggerCREAT TRIGGER nameON tableFOR DeleteASBEGINIF @@ROWCOUNT >0Delete from table where table.parentID in (select sortID from deleted);ENDthen i went to the table and i tried to delete...and it gave me an error....that there are records that have there parentID= sortID of the table i am trieng to delete...so i deleted the relationship...and kept the triggerand now ...when i delete one...it deletes one level down....but not more....i mean when i delete sortID=4it deletes all the records that has parentID=4...and NOT more..whereas my aim was to have it recursive not to have records lost in my databasehope i explained good as much as i hope to find an answer soon...a clear one...and thanks in advanced...
I have package there i have multiple tasks,I have used one User definied varible into my package level,So here my condition is i want to change my variable name from the package level,Here that variable used in different places in my package level,it has used in some places as well in my package level.
I need to change my Variable name after development of my package so how it will changed.
First of all, I've been a reader of swynk.com for quite sometime now, and I'd like to say 'thank you' to everyone who contributes.
Today, I'm the town moron.. haha I'm having issues with column level constraints. I have a varchar(50) where I want to keep *,=,#,/, .. etc, OUT OF the value input. I don't want to strip them. I simply want for sql to throw an error if the insert contains those (and other characters). The only characters that I want in the column are A-Z and 0-9. However, it's not a set number of characters per insert. It always varies... There has to be an easier way to do this than creating a constraint for every possibilty... Any help would be greatly appreciated.
Hi! when WITH (NOLOCK) statement is used in a select statement, it allows to retrieved data from a set of data locked by another transaction. Is it possible to enforce this at connection level? I mean to open a connection using sqlclient and enforce NOLOCK so that all select statements post to database using that connection are not locked by other transactions. thanks in advance
The problem that I am having is that with Visual Web Developer I am creating a webpage and having it directly put online, so for example when I start a new ASP.NET page, I select the location to be HTTP, with the location http://MYWEBSERVER/Website and for the language and Visual BasicI notice a couple of things, first that there is no longer a a link under the Main toolbar "Website" selection called the ASP.NET configuration. So how can I configure what I want to have users be able to do? It seems that this choice is only available if I am building the ASP.NET page on my "localhost". So that is the first problem. So I am able to get the pages to work, atleast the things such as the textboxes to show up etc, (Even things as advanced as the "Login" box). How ever when I try to get someone to try to login I am taken to a page that has an server error. The error is: "The SSE Provider did not find the database file specified in the connection string. At the configured trust level (below High trust level), the SSE provider can not automatically create the database file. " The Stack Trace Errors are at the bottom. I think this is happening because the automatically generated databases are not getting built online as they are on my computer. On my computer I have MSSQL express. So either the databases are not getting built for some reason, (and I think that is the case as I don't see any in the folder). So I think that somehow I have to create a database on my server, and then somehow configure the ASP.NET file, perhaps in the Web.Config file to look for that new database. Is this the correct methodology? Is there some simpler way that I can just somehow upload things as they are and have them work correctly on my server? The error says that either the Server did not find the database or that the trust level was insufficient. I don't think that is it as I just looked again and I don't see any .MDF files. So how would I go about getting this to work right? Is there a way to do this with MySQL also? So that I don't have to use MSSQL? My server only allows 1 DataBase for that. Thanks and I hope my question makes sense. It is basically how can I get it to be able to create and check users etc. online? Brian [ProviderException: The SSE Provider did not find the database file specified in the connection string. At the configured trust level (below High trust level), the SSE provider can not automatically create the database file.] System.Web.DataAccess.SqlConnectionHelper.EnsureSqlExpressDBFile(String connectionString) +2555237 System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +87 System.Web.Security.SqlMembershipProvider.GetPasswordWithFormat(String username, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& passwordFormat, String& passwordSalt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate) +1121 System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) +105 System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved) +42 System.Web.Security.SqlMembershipProvider.ValidateUser(String username, String password) +83 System.Web.UI.WebControls.Login.OnAuthenticate(AuthenticateEventArgs e) +160 System.Web.UI.WebControls.Login.AttemptLogin() +105 System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +99 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35 System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +115 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +163 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102
I have writen a Function which call's the same function it self. I'm getting the error as below.
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32). Can any one give me a solution for this problem I have attached the function also.
CREATE FUNCTION dbo.GetLegsFor(@IncludeParent bit, @EmployeeID float) RETURNS @retFindReports TABLE (EmployeeID float, Name nvarchar(255), BossID float) AS BEGIN IF (@IncludeParent=1) BEGIN INSERT INTO @retFindReports SELECT MemberId,Name,referredby FROM Amemberinfo WHERE Memberid=@EmployeeID END DECLARE @Report_ID float, @Report_Name nvarchar(255), @Report_BossID float DECLARE RetrieveReports CURSOR STATIC LOCAL FOR SELECT MemberId,Name,referredby FROM Amemberinfo WHERE referredby=@EmployeeID OPEN RetrieveReports FETCH NEXT FROM RetrieveReports INTO @Report_ID, @Report_Name, @Report_BossID WHILE (@@FETCH_STATUS = 0) BEGIN INSERT INTO @retFindReports SELECT * FROM dbo.GetLegsFor(0,@Report_ID) INSERT INTO @retFindReports VALUES(@Report_ID,@Report_Name, @Report_BossID) FETCH NEXT FROM RetrieveReports INTO @Report_ID, @Report_Name, @Report_BossID END CLOSE RetrieveReports DEALLOCATE RetrieveReports
I am running this query "delete from ims_domains where id=61" and got the error Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32)
Please let me know what should be the reason? Thanks, Ravi
I face this error when i try to run my store procedure. The sample of store procedure as following:
SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GO
CREATE PROCEDURE sp_addUserAccess with encryption AS SET NOCOUNT ON
DECLARE @COUNTER INT SET @COUNTER = 0
DECLARE @i_compId INT BEGIN DECLARE C1 SCROLL CURSOR FOR SELECT i_compId FROM ltd_cms_company WHERE (i_owner = 176 or i_owner = 268) AND ti_recStatus = 1 END
OPEN C1 FETCH ABSOLUTE @COUNTER FROM C1 INTO @i_compId
I do not insert/update/delete on the view directly.
For every insert/update in table A /B the values should get insert/update in the view respectively. This insert/update on view should invoke the trigger.
And I am unable to see this trigger work on the view if any insert/update occurs on base table level.
Trigger is working only if any operation is done directly on the view.
Hi all, I get this message when trying to update a tabel i have whichhas nested hierarchies.The current hierarchies beginning from root = 1 are up to the level 5.Before going into details and sample data with all the sql queries andprocedures, this limitation from Microsoft for nested levels .. isthere any way or trick to increase the level in generic?
I have created a delete trigger in Table1 and Table2. Once I delete a certain record in Table1 it will also delete that record in Table2 or vice versa. But once i delete certain record either in Table1 or Table2 it will create an error "Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).". Can you help me on this?
Can someone help me with the following problem: I'm a SQL server DBA and we sell intern SQL-Server resources to the application teams based on needed storage and number of users. I have several servers shared by different application teams.
Now I'm looking for a method to limit the number of users working together on a specified Database. Because when a project manager wants resources for 100 users I want to be sure that only 100 users can connect to that particular database at the same time.
I know I can limit the number of connections on server level but I need this on Db level too.
We have a need for getting data from sqlserver DB on premise to the cloud. DB is not encrypted currently, other applications are accessing it but those applications are on premise. Following link talks about encrypted connection, but is it possible to encrypt only one of the port connection. we can add a custom port.URL...
I am writing an audit trail trigger that needs to query columns, but the specific column names are not known until the trigger runs and determines what columns have changed. Once I know the changed column(s) I fetch the column name. No sweat. The problem is using a variable in place of a column name I can not get the data to return, only the column name.
-- Here is how I get the column name. It works great, @CName -- reflects the column name as I use it elsewhere fine. Select @CName = col_name(OBJECT_ID('TABContract'), @CNum)
-- This simple syntax usually works, it does not using a -- variable as the column name. @Prev is populated with -- @CName literally. I have tried various and asundry ()'s and []'s Select @Prev = @CName From Deleted
-- Here I have hard coded the Column name and ran a test modifying that column "Comment" and it works! @Prev is populated with the columns data not the Column name. Select @Prev = Comment From Deleted
-- Tried these syntaxes, no luck Select @Prev = (Select @CName From Deleted) Select @Prev = (Select col_name(OBJECT_ID('TABContract'), @CNum) From Deleted)
Hello, I have a very simple trigger that only copies the data from one table to a historial table, when a row is deleted. It works fine, but now I need to change it becouse I am inserting a new column to the table, which type is ntext, and when I try to declare a ntext variable (inside the trigger), it does not allow me. Does anyone know how to go round this? Here is the code of the trigger (maybe it is not efficient, as I am a newbie in this :D, please tell if so as well)
CREATE TRIGGER OnDelete ON dbo.Tracker FOR DELETE AS
declare @IDregistro as integer; declare @IDTIT as integer; declare @negocio as nvarchar(50); declare @fechaOr as datetime; declare @asuntoOr as nvarchar(50); declare @estadoOr as nvarchar(50); declare @descripcionOr as nvarchar(255); declare @usuarioOr as nvarchar(50); declare @contactoOr as nvarchar(50); declare @companiaOr as nvarchar(40); --declare @desc as ntext; --DOES NOT WORK!!
declare @fechaSus as datetime
select @fechaSus = getdate()
select @IDregistro = IDregistro from deleted; select @IDTIT = IDTitular from deleted; select @negocio = negocio from deleted; select @fechaOr = fecha from deleted; select @asuntoOr = asunto from deleted; select @estadoOr =estado from deleted; select @descripcionOr = descripcion from deleted; select @usuarioOr = usuario from deleted; select @contactoOr = contacto from deleted; select @companiaOr = compania from deleted;
I hope that I am just missing a step in the process somewhere. I have established a string variable called DatabaseServer and another called DatabaseName. In the OLE DB connectionstring expression I have the following:
My understanding is that changing the variable from SERVERA to SERVERB should repoint the connection. (Test to pre-production to production in my current promotion environment.) This should also take effect in any dataflow task using the database connection above right? When I try to repoint the server variable (and only the server variable) I am either a.)throwing errors saying the original connection cannot be found in the data flow task, or b.)the job appears to be processing fine, but the repoint did not take place and data is still flowing to the original server.
Can anyone offer suggestions as to what I am missing?
The properties values in the DB connection:
ConnectionManagerType is OLEDB
DataSourceID is blank
DelayValidation is False (Setting to true changes nothing in my test)
Expression for ConnectionString is (see above)
RetainSameConnection is False
SupportsDTCTTransactions is True (and appears to be unchangeable.)
I use following trigger to stop user "smith" if he try to connect through SSMS to My Server:
create TRIGGER [trg_connection_MyServer] ON ALL SERVER WITH EXECUTE AS 'Smith' FOR LOGON AS BEGIN IF ORIGINAL_LOGIN()= 'Smith' begin if exists (SELECT 1 FROM sys.dm_exec_sessions WHERE (program_name like 'Microsoft SQL Server%' and original_login_name = 'Smith') ) ROLLBACK; end
I want to log this information or send emal incase, this user try to connect through SSMS, so that I can catch it. How can I do this, if I use insert command it rollsback everything and I can't do any activity.
__________________________________________________ _ CREATE TRIGGER dbo.Fochini_Insert ON dbo.FochiniTable AFTER INSERT AS BEGIN DECLARE @v_object_key VARCHAR(80) DECLARE @v_object_name VARCHAR(40) DECLARE @v_object_verb VARCHAR(40) DECLARE @v_datetime DATETIME
SELECT ins.Cust_Id INTO @v_object_key FROM inserted ins <--- my problem area!! SET @v_object_name = 'FochiniTable' SET @v_object_verb = 'Create' SET @v_datetime = GETDATE()
IF ( USER <> 'webuser' ) INSERT INTO dbo.xworlds_events (connector_id, object_key, object_name, object_verb, event_priority, event_time, event_status, event_comment) VALUES ('Fochini', @v_object_key, @v_object_name, @v_object_verb, '1', @v_datetime,'0', 'Triggered by Customer CREATE')
END ________________________________________________
i'm trying to get the INSERTED variable from table FochiniTable on colomn Cust_Id
and the statement: SELECT ins.Cust_Id INTO @v_object_key FROM inserted ins - is failing [still a newbie on mssql server 2000]
When I deploy the cube which is sitting on my PC (local) the following 4 errors come up:
Error 1 The datasource , 'AdventureWorksDW', contains an ImpersonationMode that that is not supported for processing operations. 0 0 Error 2 Errors in the high-level relational engine. A connection could not be made to the data source with the DataSourceID of 'Adventure Works DW', Name of 'AdventureWorksDW'. 0 0 Error 3 Errors in the OLAP storage engine: An error occurred while the dimension, with the ID of 'Customer', Name of 'Customer' was being processed. 0 0 Error 4 Errors in the OLAP storage engine: An error occurred while the 'Customer Alternate Key' attribute of the 'Customer' dimension from the 'Analysis Services Tutorial' database was being processed. 0 0
Can I define a Global variable and use it as a Connection to SQL Server .
What I want to do is Create a DTS which pumps out files to an app server. However this might be done in different environments and I want to keep the SQL Connection Dynamic and change it in global parameter value.