SQL Server 2012 :: In Trigger - Building Dynamic Table With Inserted Data

Nov 4, 2015

Within a trigger, I'm trying to create a unique table name (using the NEWID()) which I can store the data that is found in the inserted and deleted tables.

Declare @NewID varchar(50) = Replace(convert(Varchar(50),NEWID()),'-','')
Declare @SQLStr varchar(8000)

Set @SQLStr= 'Select * into [TMPIns' + @newID + '] from inserted'
Exec (@SQLStr)

I get the following error: Invalid object name 'inserted'

I know I can do:

Select * into #inserted from inserted
Set @SQLStr= 'Select * into [TMPIns' + @newID + '] from #inserted'
Exec (@SQLStr)

But I don't want to use TempDB as these tables can become big and I also feel that it is redundant. Is there a way to avoid the creation of #inserted?

View 2 Replies


ADVERTISEMENT

SQL Server 2012 :: How To Get A Table Identity Inserted By Instead Of Insert Trigger

May 14, 2015

I have a problem described as follows: I have a table with one instead of insert trigger:

create table TMessage (ID int identity(1,1), dscp varchar(50))
GO
Alter trigger tr_tmessage on tmessage
instead of insert
as
--Set NoCount On
insert into tmessage

[code]....

When I execute P1 it returns 0 for Id field of @T1.

How can I get the Identity in this case?

PS: I can not use Ident_Current or @@identity as the table insertion hit is very high and can be done concurrently.Also there are some more insertion into different tables in the trigger code, so can not use @@identity either.

View 5 Replies View Related

SQL Server 2012 :: Trigger Inserted Multiple Rows After Insert

Aug 6, 2014

I create a Trigger that allows to create news row on other table.

ALTER TRIGGER [dbo].[TI_Creation_Contact_dansSLX]
ON [dbo].[_IMPORT_FILES_CONTACTS]
AFTER INSERT
AS

[code]...

But if I create an INSERT with 50 rows.. My table CONTACT and ADDRESS possess just one line.I try to create a Cursor.. but I had 50 lines with an AdressID and a ContactID differently, but an Account and an AccountId egual on my CONTACT table :

C001 - AD001 - AC001 - ACCOUNT 001
C002 - AD002 - AC001 - ACCOUNT 001
C003 - AD003 - AC001 - ACCOUNT 001
C004 - AD004 - AC001 - ACCOUNT 001
C005 - AD005 - AC001 - ACCOUNT 001

I search a means to have 50 lines differently on my CONTACT table.

C001 - AD001 - AC001 - ACCOUNT 001
C002 - AD002 - AC002 - ACCOUNT 002
C003 - AD003 - AC003 - ACCOUNT 003
C004 - AD004 - AC004 - ACCOUNT 004
C005 - AD005 - AC005 - ACCOUNT 005

View 9 Replies View Related

SQL Server 2012 :: Building Self-referencing Hierarchical Table

May 21, 2014

An example of what I am talking about is the employee table in the Adventureworks database. This has employeeID and then ManagerID, ManagerID just being the EmployeeID of the person whom the original reports to.

I know the queries for querying this type of data and even making recursive common table expressions. What I cannot seem to find is how one goes about BUILDING said table. I see all sorts of examples where people are just doing INSERT table VALUES () manually to load the table. The problem is, I need to create a table that has potentially thousands of records.

It will essentially be a dimensional map. Don't even get me started as to they why, I will just suffice to say that is what the client and project want . I have a process that will do this now, but it is not very dynamic and very hard coded. To me, there seems like there should be some sort of standardized methodology for handling this.

View 9 Replies View Related

SQL Server 2008 :: Trigger Fire On Each Inserted Row To Insert Same Record Into Remote Table

Sep 9, 2015

I have two different SQL 2008 servers, I don't have permission to create a linked server in any of them. i created a trigger on server1.table1 to insert the same record to the remote server server2.table1 using OPENROWSET

i created a stored procedure to insert this record, and i have no issue when i execute the stored procedure. it insert the recored into the remote server.

The problem is when i call the stored procedure from trigger, i get an error message.

Stored Procedure:
USE [DB1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[Code] ....

When i try to insert a new description value in the table i got the following error message:

No row was updated
the data in row 1 was not committed
Error source .Net SqlClient Data provider.
Error Message: the operation could not be performed because OLE DB
provider "SQLNCLI10" for linked server "(null)" returned message "The partner transaction manager has disabled its support for remote/network transaction.".

correct the errors entry or press ESC to cancel the change(s).

View 9 Replies View Related

Using Inserted Table In Trigger

Feb 17, 2005

hi, i am writing a trigger to log inserts,updates and deletes in a table and would like to also enter the user details ie who did the transaction. is the spid in the inserted table? if not how do i get this information?

TIA

View 3 Replies View Related

Getting Inserted Data In Trigger

Feb 22, 2007

I am using SQL Server 2000.I want to create an after insert trigger on one of my tables, but I have forgotten how I reference the inserted data to do some business logic on it. Can someone please help. Thanks Jag 

View 1 Replies View Related

Trigger, Inserted Pseudo Table?

Jul 1, 2004

I am trying to create a trigger on a table but when I check the syntax it
tells me that "The column prefix 'inserted' does not match with a table name or alias used in this query"


CREATE TRIGGER trg_Structural_GenerateBarcode ON [dbo].[tbStructuralComponentSchedule]
AFTER INSERT
AS
DECLARE @iCount int, @cBarcode char (25), @cCode char(4)
DECLARE @cProject char(7), @cComponent char(10), @iEntryID int

SELECT @cProject = inserted.fkProjectNumber, @cComponent = inserted.fkComponentID, @iEntryID = inserted.EntryID

.......
GO


How do I use the inserted pseudo table?

Mike B

View 2 Replies View Related

How To Use Table Inserted Within Exec In A Trigger?

Mar 17, 2008

I like to use the table "Inserted" within exec(), but it doesn't work because the scope is different. Does anyone have some sort of solution to this problem? The reason I am doing it this way is because I have a table consist of 200+ columns of bit types that contains permission information (The worest design i have ever seen!).






Code Snippet
--gather column names


declare @ScreenPermissions nvarchar(256)


declare c_Permission cursor
for
SELECT [name]
FROM syscolumns
WHERE id = (
SELECT id FROM sysobjects
WHERE type = 'U'
AND [NAME] = 'ScreenPermissions'
)
and [name] like 'Allow%'



open c_Permission
fetch next from c_Permission
into @ScreenPermissions
while @@fetch_status = 0
begin

exec('INSERT INTO EmployeeInRoles (EmployeeID, RoleID) ' +
'select i.EmployeeID, r.RoleID ' +
'from inserted as i ' +
' inner join ScreenPermissions AS sp on sp.EmployeeID = i.EmployeeID and sp.' + @ScreenPermissions + ' = 1 ' +
' inner join Roles AS r on r.LoweredRoleName = Lower(' + '''' + @ScreenPermissions + '''' + ')' )

fetch next from c_Permission
into @ScreenPermissions
end
close c_Permission
DEALLOCATE c_Permission

View 7 Replies View Related

Update One Table When Records Inserted In Another Table - Variables In Trigger

May 19, 2014

I am trying to update one table when records are inserted in another table.

I have added the following trigger to the table “ProdTr” and every time a record is added I want to update the field “Qty3” in the table “ActInf” with a value from the inserted record.

My problem appears to be that I am unable to fill the variables with values, and I cannot understand why it isn’t working, my code is:

ALTER trigger [dbo].[antall_liter] on [dbo].[ProdTr]
for insert
as
begin
declare @liter as decimal(28,6)

[Code] ....

View 4 Replies View Related

Is Having A Trigger That Inserts A Row In Table 'A', When A Row In Same Table Is Inserted By ADo.Net Code?

Oct 13, 2006

I want to insert a row for a Global user  in Table 'A' whenever ADO.Net code inserts a Local user row into same table. I recommended using a trigger to implement this functionality, but the DBA was against it, saying that stored proecedures should be used, since triggers are unreliable and slow down the system by placing unecessary locks on the table. Is this true OR the DBA is saying something wrong? My thinking is that Microsoft will never include triggers if they are unreliable and the DBA is just wanting to offload the extra DBA task of triggers to the programmer so that a stored procedure is getting called, so he has less headache on his hands.Thanks

View 2 Replies View Related

Trigger- Dump 'inserted' Table To Temp Table

Jul 11, 2006

I want to pass the 'inserted' table from a trigger into an SP, I think I need to do this by dumping inserted table into a temporary table and passing the temp table. However, I need to do this for many tables, and don't want to list all the column names for each table/trigger (maintenance nightmare).

Can I dump the 'inserted' table to a temp table WITHOUT specifying the column names?

View 16 Replies View Related

Viewing The "inserted" Temp Table During Trigger?

Apr 6, 2001

Having probs debugging trigger ... need to view the "inserted" table contents, how do I do this? Manuals are pants, any tricks folks?

View 1 Replies View Related

Trigger To Generate Mail If Particular Kind Of Data Get Inserted In A Tag

Feb 25, 2014

We are having xml data in a column. Is it possible to write a trigger to generate a mail if particular kind of data get inserted in a tag.

For ex:

<File AF="910" PTO="ATN_P76035_PSQO" NNO="54545465" KTNNN="AX2" KL="" AD="99" PrqnT="AX2" Stab="21545" KE="45454" TE="65465" Rsaa="BBBB" AK="54544.AX2.POEAX2.546546546.NONTP.NONTP" AK2="">

In the above xml data if we have the value 21545 in Stab tag the trigger needs to be executed and mail needs to be sent to a distribution list.

View 1 Replies View Related

How To Postpone Trigger Fire Until After Both Parent And Child Table Values Have Been Inserted

Feb 13, 2008



Hi all,

I am sure someone must have run into this before. I have a couple of tables with a parent child relationship.

I created a trigger on the insert of the parent but don't want it to fire until both the parent and child have been inserted into.

However sometimes the child may not get inserted in to at all. In other words it is a 1 to 0 or more relationship.

I created the whole insert into the parent and the child and wrapped it all up in a transaction hoping that the trigger would not fire until the transaction actually completed.

However such is not the case and it fires when the parent is inserted into but nothing is inserted into the child yet even though that is part of the transaction.

Is it possible to postpone trigger fire until after both parent and child table values have been inserted?

Thank you,
John

View 8 Replies View Related

SQL 2012 :: Dynamic Partitioning Of Table Server

Dec 3, 2014

I need Dynamic Partition of SQL Table.

1. What is the best practice for partitioning (on date column)

2. The project on which i am working correctly have a case where in i get the update of my status flag after few days (Say 15 - 30) in that case if my data got into partition table how to update and how to search which partition has my data

3. Is creating partition occupies more disk space?

4. Is every partition would need index?

View 7 Replies View Related

SQL Server 2012 :: DATE As Dynamic Table Name

Jan 13, 2015

I am trying to select data from table that have YYMM as table names, they are formatted table1410,table1411, table1412. I am trying to format it like this

declare @tablename60 varchar(50) = 'table' + SUBSTRING(CAST(DATEPART(YY,dateadd(yy, -1, getdate())) as varchar(4)),3,4) + SUBSTRING(CAST(DATEPART(MM,dateadd(mm, -1, getdate())) as varchar(2)),1,2)

But this is hard coding the YYMM, and I would like to have it pull 30,60,90 days fromthe first of the current month. I am having a bit of trouble formatting, how to accomplish this.

View 1 Replies View Related

Can't Access Inserted Table From Trigger; Msg 4104 The Multi-part Identifier ... Could Not Be Bound.

Sep 27, 2006

I'm a newbie have trouble using the "inserted" table in a trigger. When I run these SQL statements:CREATE DATABASE foobarGOUSE foobar GOCREATE TABLE foo ( fooID int IDENTITY (1, 1) NOT NULL, lastUpdated datetime, lastValue int, PRIMARY KEY(fooID))GOCREATE TABLE bar ( barID int IDENTITY (1, 1) NOT NULL, fooID int NOT NULL, [value] int NOT NULL, updated datetime NOT NULL DEFAULT (getdate()), primary key(barID), foreign key(fooID) references foo (fooID))GOCREATE TRIGGER onInsertBarUpdateFoo ON Bar FOR INSERTAS UPDATE Foo SET lastUpdated = inserted.updated, lastValue = inserted.[Value] WHERE foo.fooID = inserted.fooIDGO

I get the error message:

Msg 4104, Level 16, State 1, Procedure onInsertBarUpdateFoo, Line 4
The multi-part identifier "inserted.fooID" could not be bound.

I can get the trigger to work fine as long as I don't reference "inserted".

What am I missing?

I'm using Microsoft SQL Server Management Studio Express 9.00.2047.00 and SQL Express 9.0.1399

Thanks in advance for your help...
Larry

View 7 Replies View Related

SQL 2012 :: Data Is Re-inserted When Replication Is Done?

Sep 22, 2015

I have a transactional publication done between two databases on different Virtual machines connected with a network. I noticed that for some reason Every time replication is happening (which is every 2,5 seconds) my data is deleted on the target DB (subscriber) then re inserted.

this should not happen, old data should remain then only the new data should be inserted.

View 3 Replies View Related

SQL Server 2012 :: Dynamic Pivot Table Not Grouping

Mar 26, 2014

I have a query

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(name)

[Code] ....

and so on.

I've tried putting my group by everywhere but it's not working. I'm missing something but what?

View 9 Replies View Related

SQL Server 2012 :: Creating Dynamic Pivot Table

Jul 2, 2014

I am having trouble figuring out why the following code throws an error:

declare
@cols nvarchar(50),
@stmt nvarchar(max)
select @cols = ('[' + W.FKStoreID + ']') from (select distinct FKStoreID from VW_PC_T) as W
select @stmt = '
select *

[Code] ...

The issue that I am having is:

Msg 245, Level 16, State 1, Line 4
Conversion failed when converting the varchar value '[' to data type int.

I know that I have to use the [ ] in order to run the dynamic sql. I am not sure what is failing and why as the syntax seems to be clean to me (obviously it is not).

View 6 Replies View Related

SQL Server 2012 :: Dynamic Query On DB Table Names

Mar 9, 2015

I have query which is used to dynamically insert value but not working. We are trying to get all table names and insert dynamically to all tables by looping through table names.

declare @a varchar(max),@i int;
declare @table table(rno int, name varchar(max))
declare @b varchar(max)
insert into @table
select row_number() over( order by table_name) rno, table_name from INFORMATION_SCHEMA.tables
declare @tblname varchar(max)

[Code] .....

View 1 Replies View Related

SQL Server 2012 :: Table Variable In Dynamic Query?

Jul 2, 2015

I have started working with dynamic queries recently. I am using a table variable and need to add a join in query dynamically.

For Eg- @TableVariable

SET @query_from = @query_from + CHAR(10) + ' JOIN @TableVariable on ABC.ID = @TableVariable.ID '

BUt it gives an error that @TableVariable must be declared

View 8 Replies View Related

SQL 2012 :: Alert Not Being Inserted To Sysalerts Table

Jul 17, 2015

I've built 4 new SQL2012 Ent SP2 instances using our standard build docsscripts all of which include an alert to pick up Sev 14 bad login messages.

However when I force a bad login to test these, they work on 2 servers but not the other 2.

The ones that fail write the Sev 14 msg to the SQL Error log and Windows Eventvwr fine, but there is no entry in the sysalerts table!?.

The alert is enabled and the windows event log service is running. I've noticed that none of the other alerts I've set up write to the sysalerts table though?

i'm not concerned about that yet, just the fact its not writing to the sysalerts table in the first place.

View 1 Replies View Related

SQL Server 2012 :: Dynamic Table Pivot With Multiple Columns

Jan 23, 2014

I am trying to pivot table DYNAMICALLY but couldn't get the desired result .

Here is the code to create a table

create table Report
(
deck char(3),
Jib_in float,
rev int,
rev_insight int,
jib_out float,

[Code] .....

Code written so far. this pivots the column deck and jib_in into rows but thats it only TWO ROWS i.e the one i put inside aggregate function under PIVOT function and one i put inside QUOTENAME()

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(deck)
FROM (SELECT p.deck FROM dbo.report AS p
GROUP BY p.deck) AS x;

[Code] ....

I need all the columns to be pivoted and show on the pivoted table. I am very new at dynamic pivot. I tried so many ways to add other columns but no avail!!

View 1 Replies View Related

SQL Server 2012 :: Dynamic Query To Print Out Resultset From A Table?

Sep 9, 2015

I wan to print out the dynamic query result so that i can use as a script for some tasks.This is the scenario wher i got stuck, i am not able to print out the result as it return only the last value because of OUTPUT param limitation

Is there any way to print all the 3 INSERT stmt.

IF OBJECT_ID ('tempdb.dbo.#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp (Command varchar(8000))
INSERT INTO #temp
SELECT 'INSERT INTO Test1(column1,column2)values(1,2)'
UNION ALL
SELECT 'INSERT INTO Test2(column1,column2)values(1,2)'

[code]....

View 4 Replies View Related

SQL Server 2012 :: Convert Rows To Columns Using Dynamic PIVOT Table

Feb 3, 2015

I have this query:

SELECT TOP (100) PERCENT dbo.Filteredfs_franchise.fs_franchiseid AS FranchiseId, dbo.Filteredfs_franchise.fs_brandidname AS Brand,
dbo.Filteredfs_franchise.fs_franchisetypename AS [Franchise Type], dbo.Filteredfs_franchise.fs_franchisenumber AS [Franchise Number],
dbo.Filteredfs_franchise.fs_transactiontypename AS [Transaction Type], dbo.Filteredfs_franchise.fs_franchisestatusname AS [Status Code],

[Code] ....

I need to pivot this so I can get one row per franchiseID and multiple columns for [Franchisee Name Entity] and [Franchise Name Individual]. Each [Franchisee Name Entity] and [Franchise Name Individual] has associated percentage of ownership.

This has to be dynamic, because each FranchiseID can have anywhere from 1 to 12 respective owners and those can be any combination of of Entity and Individual. Please, see the attached example for Franchise Number 129 (that one would have 6 additional columns because there are 3 Individual owners with 1 respective Percentage of ownership).

The question is how do I PIVOT and preserve the percentage of ownership?

View 3 Replies View Related

SQL Server 2012 :: Creating A View Or Procedure From Dynamic Pivot Table

May 29, 2015

I have written a script to pivot a table into multiple columns.

The script works when run on its own but gives an error when i try to create a view or aprocedure from the same script. The temporary table #.... does not work so i have converted it to a cte.

Here is a copy of the script below

-- Dynamic PIVOT
IF OBJECT_ID('#External_Referrals') IS NULL
DROP TABLE #External_Referrals;
GO
DECLARE @T AS TABLE(y INT NOT NULL PRIMARY KEY);

[Code] ....

View 7 Replies View Related

SQL 2012 :: Check Command That Ensures Only Certain Values Inserted In Table?

Jan 14, 2015

I am trying to create a check command that ensures only A'B','c','D','E','F','G and s1, s2 can be inserted in the table, is this even applicable? Heres my code:

Create Table GRADE (
GradeVARCHAR2(1) CONSTRAINT pk_Grade PRIMARY KEY
CONSTRAINT check_grade
CHECK (substr(Grade = 'A','B','c','D','E','F','G')),

Salary_Scale VARCHAR2(2) CONSTRAINT check_SScale
CHECK (substr(Salary_Scale = 'S1', 'S2')),
)
/

View 1 Replies View Related

SQL Server 2012 :: Inserting Record In Table - Trigger Error

Aug 6, 2014

I am inserting a record in XYZ table(DB1). Through trigger it will update ABC table(DB2).

I am getting error when doing above thing. What are the roles to be set to user to avoid above problem.

View 3 Replies View Related

SQL 2012 :: How To Make Sure That All Rows Inserted Into Datamodel And Then Truncate Staging Table

May 8, 2014

In my ETL job I would like to truncate stg table but before truncating stging table, I want to make sure that all the records are inserted in the data model. The sample is as below

create table #stg (
CreateID int,
Name nvarchar(10)
)
insert into #stg
select 1, 'a' union all
select 2, 'b' union all

[Code] ....

How can I check among these tables and make sure that all values are loaded into the data model and the staging table can be truncated.

View 2 Replies View Related

SQL Server 2012 :: Day Wise And Date Range Calculation With Looping Or Dynamic Data?

May 14, 2015

I am using Sql Server 2012.

This is how I calculate the ratio of failures in an order:

31 Days Table 1 query
sum(CASE
WHEN (datediff(dd,serDATE,'2015-01-21')) >= 31 THEN 31
WHEN (datediff(dd,serDATE,'2015-01-21')) < 0 THEN 0
ELSE (datediff(dd,serDATE,'2015-01-21'))END) as 31days1 .

How do i loop and pass dates dynamically in the Datediff?

31 Failures Table 2 query
SUM(Case when sometable.FAILUREDATE BETWEEN dateadd(DAY,-31,CONVERT(DATETIME, '2015-01-21 23:59:00.0', 102))
AND CONVERT(DATETIME, '2015-01-21 23:59:00.0', 102)Then 1 Else 0 END) As Failures31,31 Day Cal(Formula) combining both Table 1 and Table 2
((365*(Convert(decimal (8,1),T2.Failures31)/T1.31day))) [31dayCal]This works fine when done for a specific order.

I want a similar kind of calculation done for day wise and month wise.

2. what approach should I be using to achieve day wise and month wise calculation?

I do also have a table called Calender with the list of dates that i can use.

View 3 Replies View Related

SQL 2012 :: Possible To Deploy A SSIS Package Without Building Integration Services Catalog On Server?

Jan 7, 2015

Is it possible to deploy a SSIS package without building an Integration Services Catalog on the server?

View 4 Replies View Related







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