Triggers - Insert Data To Another Table

May 3, 2006

How do I set up an insert trigger to copy all of the inserted data to another table?

In other words, when someone adds a new paramater in the params table, I want to automatically create a matching set of data in the goals table.

Thanks,
Krista

View 2 Replies


ADVERTISEMENT

Duplicate Tables Insert/Update In Another Table? Triggers?

Mar 6, 2002

I want to be able to duplicate every single record that is inserted or updated in a particular table to another table, but not the delete. Is the best way to set-up a trigger? If so can anyone provide me with an example of how to do this? Also could you just duplicate certain columns in the row I would you have to do all columns?

Thanks for help.

View 2 Replies View Related

SQL Server 2008 :: Insert Data Into Table Variable But Need To Insert 1 Or 2 Rows Depending On Data

Feb 26, 2015

I am writing a query to return some production data. Basically i need to insert either 1 or 2 rows into a Table variable based on a decision as to does the production part make 1 or 2 items ( The Raw data does not allow for this it comes from a look up in my database)

I can retrieve all the source data i need easily but when i come to insert it into the table variable i need to insert 1 record if its a single part or 2 records if its a twin part. I know could use a cursor but im sure there has to be an easier way !

Below is the code i have at the moment

declare @startdate as datetime
declare @enddate as datetime
declare @Line as Integer
DECLARE @count INT

set @startdate = '2015-01-01'
set @enddate = '2015-01-31'

[Code] .....

View 1 Replies View Related

Import Data To Table With Foreign Key Triggers

Oct 3, 2007

I've imported data from an Excel spreadsheet to a table that has fields to match the destination table I'm trying to populate. The destination table has an Insert trigger with several checks on certain fields to make sure they have corresponding records in other tables.

If I do a statement like
"INSERT INTO destinationTable
(
ItemId,
Product,
SuperID,
etc etc
)
SELECT * FROM oldtable"
it runs for a while then gives me error messages from the trigger and rolls back the Insert.

The trigger has code such as
"IF (SELECT COUNT(*) FROM inserted WHERE ((inserted.Product Is Not Null))) != (SELECT COUNT(*) FROM tblInProduct, inserted WHERE (tblInProduct.Product = inserted.Product))
BEGIN
(Error message code goes here)
END"

So, do I need to do an INNER JOIN to each of the related files?
When I try that, I get this error:
"Msg 121, Level 15, State 1, Line 2
The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns."
Is SQL counting the foreign key fields as separate fields, or what?

View 6 Replies View Related

Multiple Triggers On A Table Or Encapsulated Triggers

May 12, 2008

This isn€™t an problem as such, it€™s more of a debate.

If a table needs a number of update triggers which do differing tasks, should these triggers be separated out or encapsulated into one all encompassing trigger. Speaking in terms of performance, it doesn€™t make much of an improvement doing either depending upon the tasks performed. I was wondering in terms of maintenance and best practice etc. My view is that if the triggers do totally differing tasks they should be a trigger each on their own.

www.handleysonline.com

View 12 Replies View Related

T-SQL (SS2K8) :: Insert / Update Triggers When Insert Run Via Script

Oct 23, 2014

I'm working on inserting data into a table in a database. The table has two separate triggers, one for insert and one for update (I don't like it this way, but that's how it's been for years). When there is a normal insert, done via a program, it looks like the triggers work fine. When I run an insert manually via a script, the first insert trigger will run, but the update trigger will fail. I narrowed down the issue to a root cause.

This root issue is due to both triggers using the same temporary table name. When the second trigger runs, there's an error stating that a few columns don't exist. I went to my test server and test db and changed the update trigger so that the temporary table is different than the insert trigger temporary table, the triggers work fine. The weird thing is that if the temporary table already exists, when the second trigger tries to create the temporary table, I would expect it to fail and say that it already exists.I'm probably just going to update the trigger tonight and change the temporary table name.

View 1 Replies View Related

Insert Command Fails When I Want To Insert Records In Data Table

Apr 20, 2008

On my site users can register using ASP Membership Create user Wizard control.
I am also using the wizard control to design a simple question and answer  form that logged in users have access to.
it has 2 questions including a text box for Q1 and  dropdown list for Q2.
I have a table in my database called "Players" which has 3 Columns
UserId Primary Key of type Unique Identifyer
PlayerName Type String
PlayerGenre Type Sting
 
On completing the wizard and clicking the finish button, I want the data to be inserted into the SQl express Players table.
I am having problems getting this to work and keep getting exceptions.
 Be very helpful if somebody could check the code and advise where the problem is??
 
 
<asp:Wizard ID="Wizard1" runat="server" BackColor="#F7F6F3"
BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px"
DisplaySideBar="False" Font-Names="Verdana" Font-Size="0.8em" Height="354px"
onfinishbuttonclick="Wizard1_FinishButtonClick" Width="631px">
<SideBarTemplate>
<asp:DataList ID="SideBarList" runat="server">
<ItemTemplate>
<asp:LinkButton ID="SideBarButton" runat="server" BorderWidth="0px"
Font-Names="Verdana" ForeColor="White"></asp:LinkButton>
</ItemTemplate>
<SelectedItemStyle Font-Bold="True" />
</asp:DataList>
</SideBarTemplate>
<StepStyle BackColor="#669999" BorderWidth="0px" ForeColor="#5D7B9D" />
<NavigationStyle VerticalAlign="Top" />
<WizardSteps>
<asp:WizardStep runat="server">
<table class="style1">
<tr>
<td class="style4">
A<span class="style6">Player Name</span></td>
<td class="style3">
<asp:TextBox ID="PlayerName" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="PlayerName" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style5">
 
<td class="style3">
<asp:DropDownList ID="PlayerGenre" runat="server" Width="128px">
<asp:ListItem Value="-1">Select Genre</asp:ListItem>
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
</td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="PlayerGenre" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</td>
 
</tr>
</table>
  Sql Data Source
<asp:SqlDataSource ID="InsertArtist1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" InsertCommand="INSERT INTO [Playerst] ([UserId], [PlayerName], [PlayerGenre]) VALUES (@UserId, @PlayerName, @PlayerGenre)"
 
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>">
<InsertParameters>
<asp:Parameter Name="UserId" Type="Object" />
<asp:Parameter Name="PlayerName" Type="String" />
<asp:Parameter Name="PlayerGenre" Type="String" />
</InsertParameters>
 
 
</asp:SqlDataSource>
</asp:WizardStep>
 
 Event Handler
 
To match the answers to the user I get the UserId and insert this into the database to.protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
 SqlDataSource DataSource = (SqlDataSource)Wizard1.FindControl("InsertArtist1");
MembershipUser myUser = Membership.GetUser(this.User.Identity.Name);
Guid UserId = (Guid)myUser.ProviderUserKey;String Gender = ((DropDownList)Wizard1.FindControl("PlayerGenre")).SelectedValue;
DataSource.InsertParameters.Add("UserId", UserId.ToString());DataSource.InsertParameters.Add("PlayerGenre", Gender.ToString());
DataSource.Insert();
 
}
 

View 1 Replies View Related

How To Insert Data From A File Into Table Having Two Columns-BULK INSERT

Oct 12, 2007



Hi,
i have a file which consists data as below,

3
123||
456||
789||

Iam reading file using bulk insert and iam inserting these phone numbers into table having one column as below.


BULK INSERT TABLE_NAME FROM 'FILE_PATH'
WITH (KEEPNULLS,FIRSTROW=2,ROWTERMINATOR = '||')

but i want to insert the data into table having two columns. if iam trying to insert the data into table having two columns its not inserting.

can anyone help me how to do this?

Thanks,
-Badri

View 5 Replies View Related

How To Insert Several Insert Commands, Triggers?

Jan 22, 2007

Hello, what i want is simple.
This is a simple forum, it has several topics (that the users can create), when a user create a topic, its stored in forum_topics. The user can then view the topic and post a response that is store in forum_answer, the user can also add this to his favorite list, forum_favorites is simple, contains a TopicID that refers to the topic, a username of the user that has the topic on his favorite list and a auto increment id to be able to delete specified topic favorites.
Now my question is: when a user posts a answer to Topic X, i want a predefined message to be sent to post_inbox for all the users that has Topic X in their favorite list.
How can i get MS SQL 2005 to get all the users from Topic X and then loop thru them and insert a new post into post_inbox?
 
Patrick

View 2 Replies View Related

Difference Between FOR INSERT And AFTER INSERT Triggers

Jul 23, 2005

I've been reading the docs and playing around, but I'm still notgetting the difference. For instance,create table a(i int check(i>0))create table a_src(i int)gocreate unique index ai on a(i) with IGNORE_DUP_KEYgoinsert into a_src values(1)insert into a_src values(1)insert into a_src values(2)--insert into a_src values(-1)gocreate trigger a4ins on afor insertasselect * from insertedgocreate trigger afterins on aafter insertasselect * from insertedgoinsert into a select * from a_srcgodrop table adrop table a_srcI'm gettingi-----------12(2 row(s) affected)Server: Msg 3604, Level 16, State 1, Procedure a4ins, Line 4Duplicate key was ignored.i-----------12(2 row(s) affected)even the inserted quasi tables are identical.If I uncomment insert into a_src values(-1), I'm gettingServer: Msg 547, Level 16, State 1, Line 1INSERT statement conflicted with COLUMN CHECK constraint'CK__a__i__58FC18A6'. The conflict occurred in database 'ABC_1COMPEE',table 'a', column 'i'.The statement has been terminated.without any output from either trigger.So,in which situations will FOR INSERT be useful while AFTER INSERT won'tdo?in which situations will AFTER INSERT be useful while FOR INSERT won'tdo?

View 2 Replies View Related

SQL Server 2012 :: Compare Two Table Data And Insert Changed Field To Third Table

Aug 12, 2014

I want Compare two Table data and insert changed field to the third table ...

View 9 Replies View Related

SSMS Express: Create TABLE &&amp; INSERT Data Into Table - Error Msgs 102 &&amp; 156

May 18, 2006

Hi all,

I have SQL Server Management Studio Express (SSMS Express) and SQL Server 2005 Express (SS Express) installed in my Windows XP Pro PC that is on Microsoft Windows NT 4 LAN System. My Computer Administrator grants me the Administror Privilege to use my PC. I tried to use SQLQuery.sql (see the code below) to create a table "LabResults" and insert 20 data (values) into the table. I got Error Messages 102 and 156 when I did "Parse" or "Execute". This is my first time to apply the data type 'decimal' and the "VALUES" into the table. I do not know what is wrong with the 'decimal' and how to add the "VALUES": (1) Do I put the precision and scale of the decimal wrong? (2) Do I have to use "GO" after each "VALUES"? Please help and advise.

Thanks in advance,

Scott Chang

///////////--SQLQueryCroomLabData.sql--///////////////////////////
USE MyDatabase
GO
CREATE TABLE dbo.LabResults
(SampleID int PRIMARY KEY NOT NULL,
SampleName varchar(25) NOT NULL,
AnalyteName varchar(25) NOT NULL,
Concentration decimal(6.2) NULL)
GO
--Inserting data into a table
INSERT dbo.LabResults (SampleID, SampleName, AnalyteName, Concentration)
VALUES (1, 'MW2', 'Acetone', 1.00)
VALUES (2, 'MW2', 'Dichloroethene', 1.00)
VALUES (3, 'MW2', 'Trichloroethene', 20.00)
VALUES (4, 'MW2', 'Chloroform', 1.00)
VALUES (5, 'MW2', 'Methylene Chloride', 1.00)
VALUES (6, 'MW6S', 'Acetone', 1.00)
VALUES (7, 'MW6S', 'Dichloroethene', 1.00)
VALUES (8, 'MW6S', 'Trichloroethene', 1.00)
VALUES (9, 'MW6S', 'Chloroform', 1.00)
VALUES (10, 'MW6S', 'Methylene Chloride', 1.00
VALUES (11, 'MW7', 'Acetone', 1.00)
VALUES (12, 'MW7', 'Dichloroethene', 1.00)
VALUES (13, 'MW7', 'Trichloroethene', 1.00)
VALUES (14, 'MW7', 'Chloroform', 1.00)
VALUES (15, 'MW7', 'Methylene Chloride', 1.00
VALUES (16, 'TripBlank', 'Acetone', 1.00)
VALUES (17, 'TripBlank', 'Dichloroethene', 1.00)
VALUES (18, 'TripBlank', 'Trichloroethene', 1.00)
VALUES (19, 'TripBlank', 'Chloroform', 0.76)
VALUES (20, 'TripBlank', 'Methylene Chloride', 0.51)
GO
//////////Parse///////////
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '6.2'.
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'VALUES'.
////////////////Execute////////////////////
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '6.2'.
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'VALUES'.

View 7 Replies View Related

Insert Data Into A Table From Two Tables Into A Single Table Along With A Hard Coded Value?

Feb 9, 2012

I'm trying to insert data into a table from two tables into a single table along with a hard coded value.

insert into TABLE1
(THING,PERSONORGROUP,ACCESSRIGHTS)
VALUES
((select SYSTEM_ID from TABLE2 where
AUTHOR IN (select SYSTEM_ID from TABLE2 where USER_ID
=('USER1'))),(select SYSTEM_ID from TABLE2 where USER_ID
=('USER2')),255)

I get the following-

Msg 512, Level 16, State 1, Line 1

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.

Do I need to use a cursor?

View 5 Replies View Related

INSERT INTO - Data Is Not Inserted - Using #temp Table To Populate Actual Table

Jul 20, 2005

Hi thereApplication : Access v2K/SQL 2KJest : Using sproc to append records into SQL tableJest sproc :1.Can have more than 1 record - so using ';' to separate each linefrom each other.2.Example of data'HARLEY.I',03004,'A000-AA00',2003-08-29,0,0,7.5,7.5,7.5,7.5,7.0,'Notes','General',1,2,3 ;'HARLEY.I',03004,'A000-AA00',2003-08-29,0,0,7.5,7.5,7.5,7.5,7.0,'Notes','General',1,2,3 ;3.Problem - gets to lineBEGIN TRAN <---------- skipsrestINSERT INTO timesheet.dbo.table14.Checked permissions for table + sproc - okWhat am I doing wrong ?Any comments most helpful......CREATE PROCEDURE [dbo].[procTimesheetInsert_Testing](@TimesheetDetails varchar(5000) = NULL,@RetCode int = NULL OUTPUT,@RetMsg varchar(100) = NULL OUTPUT,@TimesheetID int = NULL OUTPUT)WITH RECOMPILEASSET NOCOUNT ONDECLARE @SQLBase varchar(8000), @SQLBase1 varchar(8000)DECLARE @SQLComplete varchar(8000) ,@SQLComplete1 varchar(8000)DECLARE @TimesheetCount int, @TimesheetCount1 intDECLARE @TS_LastEdit smalldatetimeDECLARE @Last_Editby smalldatetimeDECLARE @User_Confirm bitDECLARE @User_Confirm_Date smalldatetimeDECLARE @DetailCount intDECLARE @Error int/* Validate input parameters. Assume success. */SELECT @RetCode = 1, @RetMsg = ''IF @TimesheetDetails IS NULLSELECT @RetCode = 0,@RetMsg = @RetMsg +'Timesheet line item(s) required.' + CHAR(13) + CHAR(10)/* Create a temp table parse out each Timesheet detail from inputparameter string,count number of detail records and create SQL statement toinsert detail records into the temp table. */CREATE TABLE #tmpTimesheetDetails(RE_Code varchar(50),PR_Code varchar(50),AC_Code varchar(50),WE_Date smalldatetime,SAT REAL DEFAULT 0,SUN REAL DEFAULT 0,MON REAL DEFAULT 0,TUE REAL DEFAULT 0,WED REAL DEFAULT 0,THU REAL DEFAULT 0,FRI REAL DEFAULT 0,Notes varchar(255),General varchar(50),PO_Number REAL,WWL_Number REAL,CN_Number REAL)SELECT @SQLBase ='INSERT INTO#tmpTimesheetDetails(RE_Code,PR_Code,AC_Code,WE_Da te,SAT,SUN,MON,TUE,WED,THU,FRI,Notes,General,PO_Nu mber,WWL_Number,CN_Number)VALUES ( 'SELECT @TimesheetCount=0WHILE LEN( @TimesheetDetails) > 1BEGINSELECT @SQLComplete = @SQLBase + LEFT( @TimesheetDetails,Charindex(';', @TimesheetDetails) -1) + ')'EXEC(@SQLComplete)SELECT @TimesheetCount = @TimesheetCount + 1SELECT @TimesheetDetails = RIGHT( @TimesheetDetails, Len(@TimesheetDetails)-Charindex(';', @TimesheetDetails))ENDIF (SELECT Count(*) FROM #tmpTimesheetDetails) <> @TimesheetCountSELECT @RetCode = 0, @RetMsg = @RetMsg + 'Timesheet Detailscouldn''t be saved.' + CHAR(13) + CHAR(10)-- If validation failed, exit procIF @RetCode = 0RETURN-- If validation ok, continueSELECT @RetMsg = @RetMsg + 'Timesheet Details ok.' + CHAR(13) +CHAR(10)/* RETURN*/-- Start transaction by inserting into Timesheet tableBEGIN TRANINSERT INTO timesheet.dbo.table1select RE_Code,PR_Code,AC_Code,WE_Date,SAT,SUN,MON,TUE,WE D,THU,FRI,Notes,General,PO_Number,WWL_Number,CN_Nu mberFROM #tmpTimesheetDetails-- Check if insert succeeded. If so, get ID.IF @@ROWCOUNT = 1SELECT @TimesheetID = @@IDENTITYELSESELECT @TimesheetID = 0,@RetCode = 0,@RetMsg = 'Insertion of new Timesheet failed.'-- If order is not inserted, rollback and exitIF @RetCode = 0BEGINROLLBACK TRAN-- RETURNEND--RETURNSELECT @Error =@@errorprint ''print "The value of @error is " + convert (varchar, @error)returnGO

View 2 Replies View Related

Need Some Help With A Triggers (FOR INSERT)

Jan 22, 2007

Hi there
I' d like to make a trigger which will come with some kind of message ( maybe jscript?) or printout, each time
I insert new client into the Client table. Clent table has ClientID, ClientName, Address, EMail, and ContactPerson. 
Please help
 
M.D.
 
 
  
 

View 1 Replies View Related

Insert Triggers

Aug 6, 2004

I have written an Insert Trigger to examine newly inserted records and set some values. However, each time a record is inserted, all records are checked. How can I make the trigger work only on newly inserted records?

View 5 Replies View Related

Is It Possible To Insert Data Into A Table From A Temporary Table That Is Inner Join?

Mar 10, 2008

Is it possible to insert data into a table from a temporary table that is inner join?
Can anyone share an example of a stored procedure that can do this?
Thanks,
xyz789

View 2 Replies View Related

Stored Procedure For Insert Data From One Table To Another Table

Apr 25, 2006

Hi,
     I am having 2 tables. One is main table and another is history table. Whenever I update the main table, I need to insert the all the main table data to History table, before updating the main table.
Overall it is like storing the history of the table updation.
How do i write a stored procedure for this?
Anybody has done this before?
Pls help me.
 

View 1 Replies View Related

Transact SQL :: Insert Data From Temp Table To Other Table

Oct 5, 2015

I want to insert the data from temp table to other table. Only condition is, it needs to sorted based on tool number and tool date. For example if we have ten records for tool number 1000, it should be order by tool number and then based on tool_dt. Both tables doesn't have any primary keys. Please find below my code. I removed all the unnecessary columns for simple understanding. INSERT INTO tool_summary  (tool_nbr, tool_dt) select tool_nbr, tool_dt from #tool order by tool_nbr, tool_dt...But this query is not working as expected. Data is getting shuffled.

Actual Data
Expected Result

1000
1-Aug
1000
1-Feb
1000
1-Jul
1000

[code]....

View 3 Replies View Related

BULK INSERT And Triggers

May 18, 2001

Do INSERT triggers not execute on BULK INSERT statements? Do they execute only once, after all the insertions are completed?

Is there some way to get an INSERT trigger to execute on every single row of a BULK INSERT?

Am I a dope? :)

Thanks in advance.

View 3 Replies View Related

Insert Triggers And Max Values

Nov 20, 2000

I have a situation where I need to create an insert trigger on table a which will create a corresponding record in table b. However before I insert the record i must obtain the max value for the record in table b and increment it by one. I have all this working. My question is if I just put a begin and commit with this statement is there a chance that when 2 users insert at the same time the max value may be incorrect say for instance

CREATE TRIGGER tr_cms_prov_ins ON provider
FOR INSERT
as
declare @ndentPrid char(3),
@nxtgenPrid char(7),
@fname varchar(40),
@lname varchar(40)
begin tran
select @ndentPrid = max(provider_id) from providerdnt
if @ndentPrid is null
set @ndentPrid = 1
else set @ndentPrid = @ndentPrid + 1

insert into dental..provider (provider_id, first_name, last_name, collections_go_to)
select @ndentPrid, first_name, last_name','YYYYYYYYYYYYYYYNNNNN' from inserted
commit tran

Will this do it or do I need to enforce some type of locking to handle the max value. There are no inserts into
table b directly only by the trigger insert on table a

View 1 Replies View Related

Question About Triggers (after Insert)

Oct 26, 2006

Hello all,
I'm in the process of debugging a trigger i've written (which hasn't been any fun) and i have a question.

records for the table with the trigger are only inserted from a SP using an INSERT INTO ... SELECT statement. Multiple rows at a time.

question is..
does the trigger fire once for that insert into ... select or does it fire for each new row inserted by that statement. I was under the impression that it fires for each row but i'm not sure now because the table the trigger inserts to only has one row after the SP is run.

any help is greatly appreciated.
Will

View 2 Replies View Related

After Insert Triggers Problem

Apr 3, 2008

I created a trigger which looks like
Create TRIGGER UpdateGenTables3 ON AWSWQ_Quizzes
After insert as
Begin
SET NOCOUNT ON
declare @TableName varchar(20),@Title varchar(20),@code varchar(20),@Gcode varchar(20),@uppercode varchar(20), @Description varchar(50)
DECLARE DemoCursor CURSOR FOR
Select QuizID,QuizTitle from AWSWQ_Quizzes group by QuizID,QuizTitle
OPEN DemoCursor
FETCH Next From DemoCursor INTO @code,@Title
WHILE @@FETCH_STATUS = 0
BEGIN

INSERT INTO gen_tables (TABLE_NAME, CODE, SUBSTITUTE,UPPER_CODE,DESCRIPTION,OBSOLETE_DESCRIPTION)
VALUES ('PRE_REQ_TESTS', @code, '', @code, @title, '')
FETCH Next From DemoCursor INTO @code,@Title
END
CLOSE DemoCursor
DEALLOCATE DemoCursor

end

The problem with my trigger is .I am not able to insert into my table AWSWQ_Quizzes the error i get when i try to insert is

Violation of PRIMARY KEY constraint 'pkGen_TablesTABLE_NAME'. Cannot insert duplicate key in object 'Gen_Tables'. The statement has been terminated. ---> System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'pkGen_TablesTABLE_NAME'. Cannot insert duplicate key in object 'Gen_Tables'.

View 2 Replies View Related

SSIS And Insert Triggers

Nov 9, 2005

I have created a simple data import package using the SSIS Import and Export Wizard in Visual Studio 2005. All done in a bout 2 min. great stuff.

View 4 Replies View Related

T-SQL DML Triggers And Conditions On Insert

Apr 21, 2008

Hi everyone,

I have been trying to implement a trigger that is fired when a record is inserted in a table, provided that certain fields in the inserted record meet specific criteria (what you'd find in a where clause). All examples I have come across so far involve cases where the trigger is fired off everytime there is an insert regardless of what values are being inserted.

Basically, Assume a table "Address" with colums House Number, Street Name, City, State, Zip Code. How do I make my trigger fire ONLY when a record with City = 'Boston' is inserted??


Thanks.

View 6 Replies View Related

Insert Data To A Table Where Select Data From Another SERVER

Oct 8, 2007

I had a function like below :Public Sub Getdata2(ByVal query, ByVal db, ByVal name)
Dim selectSQL As StringDim con As SqlConnection
Dim cmd As SqlCommand
Dim reader As SqlDataReader
Trycon = New SqlConnection("User ID=xxx;password=xxx;persist security info=True;Initial Catalog=database1;Data Source=xxx.xxx.xxx.xxx.xxx,xxxxx;")
Dim username As String
username = Request.QueryString("username")
selectSQL = "SET DATEFORMAT DMY;Insert into table1(hse_num, st_name, proj_name, unit_num, postal, n_postal, flr_area, flr_sf, flr_rate, flr_ra_sf, land_area, land_sf, land_rate, lnd_ra_sf, prop_code, cont_date, title, sisv_ref, r_date, rec_num, source, username, DGP, Remarks, Sub_Code, caveat, consider, age) select hse_num, st_name, proj_name, unit_num, postal, n_postal, flr_area, flr_sf, flr_rate, flr_ra_sf, land_area, land_sf, land_rate, lnd_ra_sf, prop_code, cont_date, title, sisv_ref, r_date, rec_num, source, '" & username & "', DGP, Remarks, Sub_Code, caveat, consider, age from [yyy.yyy.yyy.yyy,yyyy].database2.dbo.table2 where " & querycmd = New SqlCommand(selectSQL, con)
con.Open()
reader = cmd.ExecuteReader()
lbl.Text = selectSQLCatch ex As Exception
lbl.Text = ex.Message
Finally
If (Not con Is Nothing) Then
con.Close()
con.Dispose()
End If
End Try
End Sub
'------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
May i know that how do i retrieve data from  [yyy.yyy.yyy.yyy,yyyy].database2.dbo.table2 due to diffrent server, diffrent UID and Password
 

View 1 Replies View Related

Ntext And Update/insert Triggers

Jul 23, 2005

SQL Server 2000 : I have a series of tables which all have the samestructure. When any of these tables are modified I need to syncrhoniseall of those modifications with one other table wich is a sort of mergeof the individual tables with one extra column.For most of these tables this is not a problem. The problem arriveswhen one of the tables has an ntext column which obviously can not beused in an update or insert trigger.Here's an example of one of them:CREATE TABLE tblImages(ID INT IDENTITY(1,1) PRIMARY KEY,Inventory nvarchar(8) NOT NULL,Coll nvarchar(8) NOT NULL,ImageFile nvarchar(128) NOT NULL,ImageNotes ntext NULL,TS timestamp NULLCONSTRAINT U_Images UNIQUE NONCLUSTERED (ItemCode, Inventory, Coll,ImageFile)I then had created an update trigger which looked like this:CREATE TRIGGER COLLNAME_UTRIGGER ON COLLNAME_ImagesFOR UPDATEASBEGINUPDATE tblImages SETInventory = inserted.Inventory,Coll = 'COLLNAME',ImageFile = inserted.ImageFileName,FROM inserted INNER JOIN tblImages ON inserted.ItemCode =tblImages.ItemCode ANDinserted.Invventory = tblImages.Invventory AND tblImages.Coll ='COLLNAME' ANDinserted.ImageFileName = tblImages.ImageFileUPDATE tblImagesSET ImageNotes=inserted.NotesFROM inserted INNER JOIN tblImages ON inserted.ItemCode =tblImages.ItemCode ANDinserted.Inventory= tblImages.Inventory AND tblImages.Coll ='COLLNAME' ANDinserted.ImageFileName = tblImages.ImageFileEND " & vbCrLf)The first update in my trigger, be it an update or insert trigger,works fine. It crashes with the "Cannot use text, ntext or imagecolumns in the 'inserted' or 'deleted' tables." error in the secondpart.I have read various messages through the Internet on this and severalof them reference using INSTEAD OF triggers and views. I have neverused those before as this is my first work with SQL 2000. None of theexamples of INSTEAD OF triggers I have seen yet use the actual insertedtables and I haven't quite understood how to use them correctly.Can someone help me with the basic syntax as this trigger is one ofseveral that I am going to have to get working.Thank you in advance for any help, assistance, suggestions or"direction pointing" you may provide.

View 1 Replies View Related

Insert And Reformat Data - Table A To Table B

Jun 5, 2008

Hello,
I have a table called #table1 which is populated as in the example below.
I would like to write a selectinsert statement based on #table1 that populates #table2 like in the #table2 example.
Note #table2 is a fixed table that follows the structure below.

Can any of you T-SQL gurus help me with my problem?
Any help will be most appreciated.
Thanks

---------------------------------------------
/*
Please paste T-SQL into query window
*/
---------------------------------------------
CREATE TABLE #table1
--max of 5 orders
(
custID nvarchar(6),
dateorder [datetime] NULL,
order1 nvarchar(2),
order2 nvarchar(2),
order3 nvarchar(2),
order4 nvarchar(2),
order5 nvarchar(2)
)

GO
SET ANSI_PADDING OFF

Insert into #table1
select '012345','2008-04-19 00:00:00.000' , '01', '06', '05', null, null UNION all
select '012345','2008-04-20 00:00:00.000' , '01', '07', '05', '07', '03' UNION all
select '012345','2008-04-21 00:00:00.000' , '01', '06', null, null, null UNION all
select '012345','2008-04-22 00:00:00.000' , '01', '02', '05', '07', null UNION all
select '012345','2008-04-23 00:00:00.000' , '03', '06', null, null, null UNION all
select '987654','2008-04-21 00:00:00.000' , '19', '21', null, null, null UNION all
select '987654','2008-04-22 00:00:00.000' , '01', '02', '05', '16', null UNION all
select '987654','2008-04-23 00:00:00.000' , '03', '06', null, null, null

select * from #table1

--This is the table i would like to insert my data into
CREATE TABLE #table2
--max of 5 orders in 1 day
--it does not matter what date the date order was made the 1st date would appear in dateorder1 and so on...
(
custID nvarchar(6),
dateorder1 [datetime] NULL,
order1_1 nvarchar(2),
order1_2 nvarchar(2),
order1_3 nvarchar(2),
order1_4 nvarchar(2),
order1_5 nvarchar(2),
dateorder2 [datetime] NULL,
order2_1 nvarchar(2),
order2_2 nvarchar(2),
order2_3 nvarchar(2),
order2_4 nvarchar(2),
order2_5 nvarchar(2),
dateorder3 [datetime] NULL,
order3_1 nvarchar(2),
order3_2 nvarchar(2),
order3_3 nvarchar(2),
order3_4 nvarchar(2),
order3_5 nvarchar(2),
dateorder4 [datetime] NULL,
order4_1 nvarchar(2),
order4_2 nvarchar(2),
order4_3 nvarchar(2),
order4_4 nvarchar(2),
order4_5 nvarchar(2),
dateorder5 [datetime] NULL,
order5_1 nvarchar(2),
order5_2 nvarchar(2),
order5_3 nvarchar(2),
order5_4 nvarchar(2),
order5_5 nvarchar(2)
)

Insert into #table2
select '012345','2008-04-19 00:00:00.000' , '01', '06', '05', null, null, '2008-04-20 00:00:00.000' , '01', '07', '05', '07', '03','2008-04-21 00:00:00.000' , '01', '06', null, null, null,'2008-04-22 00:00:00.000' , '01', '02', '05', '07', null,'2008-04-23 00:00:00.000' , '03', '06', null, null, null UNION all
select '987654','2008-04-21 00:00:00.000' , '19', '21', null, null, null ,'2008-04-22 00:00:00.000' , '01', '02', '05', '16', null,'2008-04-23 00:00:00.000' , '03', '06', null, null, null , null, null, null, null, null, null, null, null, null, null, null, null

select * from #table2


drop table #table1
drop table #table2

----------------------------------------

View 2 Replies View Related

Transact SQL :: Insert Data To Different Table From Other Table

Aug 22, 2015

we have a table below

TABLE1
ID         Roll        Name         Amount     . . . . . . so on
---------------------------------------
1            2           Alex            500
2            5           Jones          600
3            2           Ales            400

and we have TABLE 2

ID         Roll        Name         Amount   . . . . . . . so on

In both the Tables ID Field is Identity Field and rest all the columns are identical in both the tables.I want to perform a query in such a way that SQL Should,

1) Remove all data from TABLE2 First
2) Select those records from TABLE1 where Roll = 2
3) Then, Insert the results to TABLE 2

So we should get the result similar to below:

ID         Roll        Name         Amount   . . . . . . . so on
---------------------------------------
1            2           Alex            500
3            2           Ales            400

how can I do this in a same sql statement.

View 3 Replies View Related

Insert Data From A Table Into A Table Of A Different Database

Sep 24, 2006



I have two databases in SQL Server and they both have almost the same tables. I want to insert the data of a table from the first database into a table with the same name, but from the second database. How can i do this?

View 1 Replies View Related

DB Design :: Insert Data From One Table To Another Table

Jul 30, 2015

I have to tables like given below Landing table "A" (Data load will happen over here, No primary keys mentioned over here) table "B" .Now I want to move the data from A to B.I have made use of below query insert into B select * from A...Landing table "A" has huge no of records, MS SQL server is taking huge amount of time.any alternative way to make this insertion process faster?

View 6 Replies View Related

Triggers Not Recognized When Running SP To Insert Set Of Records

Jan 31, 2000

I wrote a trigger that works fine when I insert record by record in the DB.
However, when I run a Stored Proc to insert a bunch of records at the same time, the trigger only works for the last record.

Anyone has a clue or a possible solution.
The trigger is well tested and works fine.

Best Regards,

Gabriel Cohen
gabrielc@yahoo.com

View 1 Replies View Related

Create Triggers In Sql7 INSERT In Sql6.5

Nov 19, 1999

I want create trigger in sql7 insert or update in data base sql6.5





Quiero crear un trigger en sql7 que haga un Insert o update en una base de datos de sql6.5, se puede y como?

View 2 Replies View Related







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