INSERT Statement Being Truncated

Nov 29, 2007

Hello all,

I have a COM object (written in VB6) that uses the Microsoft Remote Data Object 2.0 (MSRDO20.dll) to perform non-exotic SQL statements (i.e. SELECTs, INSERTs, UPDATEs and DELETE).

I am using SQL Server 2000 with SP4.

Some of our INSERT statements are being truncated within SQL2K...

We have turned on the SQL Profiler to verify this. Using our own logging mechanism, we log the INSERT SQL being passed to SQL2K immediately before executing the MS SQL statement and our log shows that the INSERT statement is indeed correct. However, we get a SQL error back due to malformed SQL. The SQL Profiler shows that the last 10 bytes have been truncated from the INSERT SQL within SQL2K.

The INSERT statement that we are passing is in the following form...

INSERT (column names...) VALUES (...)

There are embedded CRs (0x0D) in the INSERT.
The length of the INSERT being passed to SQL2K is 2243 bytes.
The length of the INSERT from the Profiler is 2233 bytes (the last 10 bytes were truncated).

Here's a brief glimpse of our VB6 code...


Dim Cn as rdoConnection

Dim sSql as String



Set Cn = New rdoConnection

Cn.Connect = "DSN=FrontOff;UID=Front;PWD=Front;DATABASE=FrontOff;"

Cn.CursorDriver = iCursorDriver

Cn.LoginTimeout = 5

Cn.QueryTimeout = 5

Cn.EstablishConnection rdDriverNoPrompt



sSql = "INSERT INTO PLU €¦"



Cn.QueryTimeout = 300
// Log sSQL to our logging mechanism...

Cn.Execute sSql, rdExecDirect


So, is there a maximum length for a SQL statement in SQL2K???

Any help would be appreciated.

TIA!!!


View 1 Replies


ADVERTISEMENT

String Or Binary Data Would Be Truncated.The Statement Has Been Terminated.

Jul 13, 2007

i am showing one field from database which is varchar and has length 1000, in the text box. i apend some text in the texbox and click update button.  on update button's click i UPDATE whole text again to database.
so when the 1000 limit crosses it stops appending text to datafield.
if i execute the query in query analyzer it shows error "String or binary data would be truncated.The statement has been terminated."
 on my web form how can i catch this sql exception so that i can give error message on the form?
thanks in advance

View 2 Replies View Related

String Or Binary Data Would Be Truncated.The Statement Has Been Terminated.

Oct 5, 2007

hi i am successfully uploading a image and that path is stored in label Now what i want is to store that label path(image path) in database not image only path
 while i executing this programe i got this error.This is code.I got error at sqlcmd.ExecuteNonQuery().
code:
labelRes1.Text = RadUploadContext.Current.UploadedFiles [File1.UniqueID].FileName;
 string imgpath = labelRes1.Text; SqlConnection sqlcon = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DiskEra;Data Source=MAINSERVER");
sqlcon.Open();
 SqlCommand sqlcmd = new SqlCommand("insert into tblCategories(ImagePath ) values (@ImagePath)", sqlcon);
sqlcmd.Parameters.AddWithValue("@ImagePath",imgpath );
sqlcmd.ExecuteNonQuery();
 
 priority: very very high
regards;
kishore
 

View 1 Replies View Related

String Or Binary Data Would Be Truncated. The Statement Has Been Terminated.

Jan 10, 2008

The code below the error produces the error, please help. String or binary data would be truncated.The statement has been
terminated. Description:
An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and
where it originated in the code. Exception Details:
System.Data.SqlClient.SqlException: String or binary data would be
truncated.The statement has been terminated.Source Error:




Line 236: ins.Parameters(i).Value = r(i)Line 237: NextLine 238: ins.ExecuteNonQuery()Line 239: 'If System.Threading.Interlocked.Increment(rowscopied) Mod 10000 = 0 ThenLine 240: 'Console.WriteLine("-- copied {0} rows.", rowscopied)Source
File: C:Inetpubwwwrootsitesmarketingappsdispositiondefault.aspx.vb
   Line: 238  -------------  Private Shared Sub InsertData(ByVal sourceTable As System.Data.DataTable, ByVal destConnection As SqlConnection)        ' old method: Lots of INSERT statements         Dim rowscopied As Integer = 0        ' first, create the insert command that we will call over and over:         destConnection.Open()        Using ins As New SqlCommand("INSERT INTO [tblAppointmentDisposition] ([contactdate], [dnbnumber], [prospectname], [businessofficer], [phonemeeting], [followupcalldate2], [phonemeetingappt], [followupcalldate3], [appointmentdate], [appointmentlocation], [appointmentkept], [applicationgenerated], [applicationgenerated2], [applicationgenerated3], [comments], [newaccount], [futureopportunity]) VALUES (@contactdate, @dnbnumber, @prospectname, @businessofficer, @phonemeeting, @followupcalldate2, @phonemeetingappt, @followupcalldate3, @appointmentdate, @appointmentlocation, @appointmentkept, @applicationgenerated, @applicationgenerated2, @applicationgenerated3, @comments, @newaccount, @futureopportunity)", destConnection)            ins.CommandType = CommandType.Text            ins.Parameters.Add("@contactdate", SqlDbType.NVarChar)            ins.Parameters.Add("@dnbnumber", SqlDbType.NVarChar)            ins.Parameters.Add("@prospectname", SqlDbType.Text)            ins.Parameters.Add("@businessofficer", SqlDbType.NChar)            ins.Parameters.Add("@phonemeeting", SqlDbType.NVarChar)            ins.Parameters.Add("@followupcalldate2", SqlDbType.NVarChar)            ins.Parameters.Add("@phonemeetingappt", SqlDbType.NVarChar)            ins.Parameters.Add("@followupcalldate3", SqlDbType.NVarChar)            ins.Parameters.Add("@appointmentdate", SqlDbType.NVarChar)            ins.Parameters.Add("@appointmentlocation", SqlDbType.NVarChar)            ins.Parameters.Add("@appointmentkept", SqlDbType.NVarChar)            ins.Parameters.Add("@applicationgenerated", SqlDbType.NVarChar)            ins.Parameters.Add("@applicationgenerated2", SqlDbType.NVarChar)            ins.Parameters.Add("@applicationgenerated3", SqlDbType.NVarChar)            ins.Parameters.Add("@comments", SqlDbType.Text)            ins.Parameters.Add("@newaccount", SqlDbType.NVarChar)            ins.Parameters.Add("@futureopportunity", SqlDbType.NVarChar)            ' and now, do the work:             For Each r As DataRow In sourceTable.Rows                For i As Integer = 0 To 16                    ins.Parameters(i).Value = r(i)                Next                ins.ExecuteNonQuery()                'If System.Threading.Interlocked.Increment(rowscopied) Mod 10000 = 0 Then                'Console.WriteLine("-- copied {0} rows.", rowscopied)                'End If            Next        End Using        destConnection.Close()    End Sub

View 2 Replies View Related

String Or Binary Data Would Be Truncated. The Statement Has Been Terminated.

Sep 30, 2004

I am working on Updating information from a table using Sql Server, but I keep receiving the error "String or binary data would be truncated. The statement has been terminated."
I have changed my maxlength of each textbox to equal the columns of my table but keep receiving the same answer. I also increased the lengths to make sure there was enough space, but no successful ending. Can anyone help? Here is my code and error message.

***************************************************************************
Sub btnSubmit_Click( s As Object, e As EventArgs )
Dim strUpdate As String
Dim cmdSelectData3 As SqlCommand
Dim conMyData As SqlConnection


conMyData = New SqlConnection("Server=helpdesk01; UID=sa;
PWD=****; database=ASPState" )


cmdSelectData3 = New SqlCommand("MemberUpdate", conMyData)
cmdSelectData3.CommandType = CommandType.StoredProcedure
cmdSelectData3.Parameters.Add("@MTitle", radMr.Text)
cmdSelectData3.Parameters.Add("@First", trim(txtFirstname.text))
cmdSelectData3.Parameters.Add("@Middle", trim(txtMiddlename.Text))
cmdSelectData3.Parameters.Add("@Last", trim(txtLastname.text))
cmdSelectData3.Parameters.Add("@Country", trim(dropCountry.SelectedItem.text))
cmdSelectData3.Parameters.Add("@Email", trim(txtEmail.text))
cmdSelectData3.Parameters.Add("@Promo", chkPromoUpdate.text)
cmdSelectData3.Parameters.Add("@Genre", trim(dropGenre.SelectedItem.text))

conMyData.Open()

cmdSelectData3.ExecuteNonQuery() (**error in Red**)

conMyData.Close()
End Sub


*************************************************************************

View 4 Replies View Related

String Or Binary Data Would Be Truncated. The Statement Has Been Terminated

May 11, 2005

hello,
can you help to solve this problem. I have an asp.net application and when i try to insert the record in SqlServer table this error appears, just give me the solution please. iam so
String or binary data would be truncated. The statement has been terminated
Line 21:     cmd.Parameters.Add(New SQLParameter("@email", frmemail.text))Line 22:     myConn.open()Line 23:     cmd.ExecuteNonQueryLine 24:     MyConn.Close()Line 25:     label1.visible="true"

View 1 Replies View Related

Text Truncated On INSERT (urgent)

Mar 14, 2006

Hi,Question: Why is INSERT of a string having 8000+ characters causing truncation in a TEXT field?We are working on a website for a client, and one of their CMS-driven pages contains more than 8000 chars for its content. The database field was originally TEXT datatype at the default size, but the content was getting truncated upon INSERT. So I looked into why this was happening, tried many things including: 1. Executing: EXEC sp_tableoption 'section', 'text in row', '7000'2. Changing datatype from TEXT to VARCHAR(8000). (of course this truncated at 8000).And this truncation still occurring. This is happening on SQL Server 2000 installed and configured on our client's server. The servers we host don't have this problem, and we have even tested the INSERT on our server and it does not truncate. So why is it truncating only on our client's Sql Server? Is there some kind of default configuration setting that limits the allowable length?I'm not intimately familiar with the large BLOB datatypes, and haven't really needed to deal with this issue before now. Now the client is upset about the limitation and does not wish to copy edit the content for their webpage. This is an urgent matter. I need to figure out the problem within a few hours today (it is morning in Europe on Tuesday 14 mar 2006 right now). Thanks in advance.UPDATE: I HAVE RESOLVED THE ISSUE. THE PROBLEM WAS A RESTRICTION IN THE STORED PROCEDURE INPUT VARIABLE DECLARATION -- WAS TRUNCATING AT 8000 CHARACTERS.

View 13 Replies View Related

Data Getting Truncated As I Insert I.e. Instead Of Inserting Hello It Inserts 'H'

Jul 25, 2005

m inserting some data in big-sized field
and small-sized fields, data of varchar type, int's, dateTime, and
others... i am using something called a stored procedure to add data
into a table.. now when i execute the stored procedure my data gets
truncated (although i made the sizes for my fields ridiculously big
like 1000 just in case) for example if i want to enter Jasmine it only
inserts 'J' in the field

I am sure there's something wrong in the stored procedure, and I am
guessing it's a problem of using single vs. double quotes and stuff
like that within my insert statement...
the following is my stored procedure:

CREATE procedure addLabor
@lName varchar,
@fName varchar,
@mName varchar,
@title varchar,
@craft varchar,
@lastFour varchar,
@SSN varchar,
@dateOfHire varchar,
@currentProj varchar,
@status tinyInt,
@project_id int,
@updateBy varchar,
@updateDate varchar,
@address varchar,
@email varchar,
@phone varchar,
@zip varchar,
@myfeedBack varchar,
@ethnicity varchar,
@userID int
as
BEGIN
SET NOCOUNT OFF
DECLARE @newid INT
insert into laborPersonal ( lName, fName, mName, title, craft,
lastFour, SSN, dateOfHire,  currentProj, status, project_id,
updateBy,

updateDate, address, email, phone, zip, ethnicity)
 VALUES
(@lName  , @fName , @mName , @title  , @craft , @lastFour  , @SSN ,@dateOfHire  , @currentProj ,
@status,  @project_id , @UpdateBy, @UpdateDate , @address , @email , @phone , @zip , @ethnicity )
SELECT @newid = SCOPE_IDENTITY()
insert into feedBack
(lID, feedBack, userID, project_id)
values
(@newid ,+'
+@myfeedBack + ',
+@userID  ,
@project_id )
SET NOCOUNT ON
END
GO


When i use 2 single quotes it insert the following string: "@lName" not the actual value of the variable @lName
my exec statement is this:
EXEC addLabor 'Razor', 'Nazor', 'mid', 'Mr', 'Carpenter Forman',
'1234',
'keOWVozC+wmBvaqgkVkZci5y4vFLdTKfZOVG4C6BSN6H2MBP6pdsIWA0SdPAlPJra0EjEj+uXI/kXSiBuwwnKQ==',
'6/27/2005 12:00:00 AM' , 'O.C. Public Library', 1, 3, '3', '7/25/2005
2:38:02 PM', '1233 Shady Canyon, Irvine', '', '', '12345',
'123-12-1234', 'African American', '3'

I appreciate any help or hints
thanks to all

View 1 Replies View Related

Retrieve Truncated Data From BULK INSERT?

Jan 10, 2007

Hi everyone. Does anyone know if you can retrieve truncated data from a BULK INSERT operation?

We have a file that needs to be inserted into a SQL Server Database. There is a field that has a maximum of 8000 characters, but some times users submit files that have more than that. We need to be able to capture the truncated data. The BULK INSERT operation does not throw an error. The only way I can think of to get the data is if I bulk insert the data into a temporary table with a memo field and then copy it over, but that may really slow down the SP.

Has anyone encountered this situation before? I also have the option of parsing the file in .NET.

Thanks and take care,

Angel

View 9 Replies View Related

Insert Error :String Or Binary Data Would Be Truncated.

Feb 13, 2001

Hi, got this sql statement, I am not sure why I am getting this error message at the botton. Thanks for your input:

insert into generator(member_id,contact_id,company_name,contac t_fname)
select member_id,contact_id,company_name,contact_fname
from customer

Server: Msg 8152, Level 16, State 9, Line 1
String or binary data would be truncated.
The statement has been terminated.

Thanks

View 1 Replies View Related

DB Engine :: Can't Use The MERGE Statement / How To Design WHERE Condition For Insert Statement

Nov 5, 2015

I've have a need with SQL Server 2005 (so I've no MERGE statement), I have to merge 2 tables, the target table has 10 fields, the first 4 are the clustered index and primary key, the source table has the same fields and index.Since I can't use the MERGE statement (I'm in SQL 2005) I have to make a double step operation, and INSERT and an UPDATE, I can't figure how to design the WHERE condition for the insert statement.

View 2 Replies View Related

Strange Problem: SQL Insert Statement Does Not Insert All The Fields Into Table From Asp.net C# Webpage

Apr 21, 2008

An insert statement was not inserting all the data into a table. Found it very strange as the other fields in the row were inserted. I ran SQL profiler and found that sql statement had all the fields in the insert statement but some of the fields were not inserted. Below is the sql statement which is created dyanmically by a asp.net C# class. The columns which are not inserted are 'totaltax' and 'totalamount' ...while the 'shipto_name' etc...were inserted.there were not errors thrown. The sql from the code cannot be shown here as it is dynamically built referencing C# class files.It works fine on another test database which uses the same dlls. The only difference i found was the difference in date formats..@totalamount=1625.62,@totaltax=125.62are not inserted into the database.Below is the statement copied from SQL profiler.exec sp_executesql N'INSERT INTO salesorder(billto_city, billto_country, billto_line1, billto_line2, billto_name,billto_postalcode, billto_stateorprovince, billto_telephone, contactid, CreatedOn, customerid, customeridtype,DeletionStateCode, discountamount, discountpercentage, ModifiedOn, name, ordernumber,pricelevelid, salesorderId, shipto_city, shipto_country,shipto_line1, shipto_line2, shipto_name, shipto_postalcode, shipto_stateorprovince,shipto_telephone, StateCode, submitdate, totalamount,totallineitemamount, totaltax ) VALUES(@billto_city, @billto_country, @billto_line1, @billto_line2,@billto_name, @billto_postalcode, @billto_stateorprovince, @billto_telephone, @contactid, @CreatedOn, @customerid,@customeridtype, @DeletionStateCode, @discountamount,@discountpercentage, @ModifiedOn, @name, @ordernumber, @pricelevelid, @salesorderId,@shipto_city, @shipto_country, @shipto_line1, @shipto_line2,@shipto_name, @shipto_postalcode, @shipto_stateorprovince, @shipto_telephone,@StateCode, @submitdate, @totalamount, @totallineitemamount, @totaltax)',N'@billto_city nvarchar(8),@billto_country nvarchar(13),@billto_line1 nvarchar(3),@billto_line2 nvarchar(4),@billto_name nvarchar(15),@billto_postalcode nvarchar(5),@billto_stateorprovince nvarchar(8),@billto_telephone nvarchar(3),@contactid uniqueidentifier,@CreatedOn datetime,@customerid uniqueidentifier,@customeridtype int,@DeletionStateCode int,@discountamount decimal(1,0),@discountpercentage decimal(1,0),@ModifiedOn datetime,@name nvarchar(33),@ordernumber nvarchar(18),@pricelevelid uniqueidentifier,@salesorderId uniqueidentifier,@shipto_city nvarchar(8),@shipto_country nvarchar(13),@shipto_line1 nvarchar(3),@shipto_line2 nvarchar(4),@shipto_name nvarchar(15),@shipto_postalcode nvarchar(5),@shipto_stateorprovince nvarchar(8),@shipto_telephone nvarchar(3),@StateCode int,@submitdate datetime,@totalamount decimal(6,2),@totallineitemamount decimal(6,2),@totaltax decimal(5,2)',@billto_city=N'New York',@billto_country=N'United States',@billto_line1=N'454',@billto_line2=N'Road',@billto_name=N'Hillary Clinton',@billto_postalcode=N'10001',@billto_stateorprovince=N'New York',@billto_telephone=N'124',@contactid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@CreatedOn=''2008-04-18 13:37:12:013'',@customerid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@customeridtype=2,@DeletionStateCode=0,@discountamount=0,@discountpercentage=0,@ModifiedOn=''2008-04-18 13:37:12:013'',@name=N'E-Commerce Order (Before billing)',@ordernumber=N'BRKV-CC-OKRW5764YS',@pricelevelid='B74DB28B-AA8F-DC11-B289-000423B63B71',@salesorderId='9CD0E11A-5A6D-4584-BC3E-4292EBA6ED24',@shipto_city=N'New York',@shipto_country=N'United States',@shipto_line1=N'454',@shipto_line2=N'Road',@shipto_name=N'Hillary Clinton',@shipto_postalcode=N'10001',@shipto_stateorprovince=N'New York',@shipto_telephone=N'124',@StateCode=0,@submitdate=''2008-04-18 14:37:10:140'',@totalamount=1625.62,@totallineitemamount=1500.00,@totaltax=125.62
 
thanks

View 7 Replies View Related

Cannot INSERT Data To 3 Tables Linked With Relationship (INSERT Statement Conflicted With The FOREIGN KEY Constraint Error)

Apr 9, 2007

Hello
 I have a problem with setting relations properly when inserting data using adonet. Already have searched for a solutions, still not finding a mistake...
Here's the sql management studio diagram :

 and here goes the  code1 DataSet ds = new DataSet();
2
3 SqlDataAdapter myCommand1 = new SqlDataAdapter("select * from SurveyTemplate", myConnection);
4 SqlCommandBuilder cb = new SqlCommandBuilder(myCommand1);
5 myCommand1.FillSchema(ds, SchemaType.Source);
6 DataTable pTable = ds.Tables["Table"];
7 pTable.TableName = "SurveyTemplate";
8 myCommand1.InsertCommand = cb.GetInsertCommand();
9 myCommand1.InsertCommand.Connection = myConnection;
10
11 SqlDataAdapter myCommand2 = new SqlDataAdapter("select * from Question", myConnection);
12 cb = new SqlCommandBuilder(myCommand2);
13 myCommand2.FillSchema(ds, SchemaType.Source);
14 pTable = ds.Tables["Table"];
15 pTable.TableName = "Question";
16 myCommand2.InsertCommand = cb.GetInsertCommand();
17 myCommand2.InsertCommand.Connection = myConnection;
18
19 SqlDataAdapter myCommand3 = new SqlDataAdapter("select * from Possible_Answer", myConnection);
20 cb = new SqlCommandBuilder(myCommand3);
21 myCommand3.FillSchema(ds, SchemaType.Source);
22 pTable = ds.Tables["Table"];
23 pTable.TableName = "Possible_Answer";
24 myCommand3.InsertCommand = cb.GetInsertCommand();
25 myCommand3.InsertCommand.Connection = myConnection;
26
27 ds.Relations.Add(new DataRelation("FK_Question_SurveyTemplate", ds.Tables["SurveyTemplate"].Columns["id"], ds.Tables["Question"].Columns["surveyTemplateID"]));
28 ds.Relations.Add(new DataRelation("FK_Possible_Answer_Question", ds.Tables["Question"].Columns["id"], ds.Tables["Possible_Answer"].Columns["questionID"]));
29
30 DataRow dr = ds.Tables["SurveyTemplate"].NewRow();
31 dr["name"] = o[0];
32 dr["description"] = o[1];
33 dr["active"] = 1;
34 ds.Tables["SurveyTemplate"].Rows.Add(dr);
35
36 DataRow dr1 = ds.Tables["Question"].NewRow();
37 dr1["questionIndex"] = 1;
38 dr1["questionContent"] = "q1";
39 dr1.SetParentRow(dr);
40 ds.Tables["Question"].Rows.Add(dr1);
41
42 DataRow dr2 = ds.Tables["Possible_Answer"].NewRow();
43 dr2["answerIndex"] = 1;
44 dr2["answerContent"] = "a11";
45 dr2.SetParentRow(dr1);
46 ds.Tables["Possible_Answer"].Rows.Add(dr2);
47
48 dr1 = ds.Tables["Question"].NewRow();
49 dr1["questionIndex"] = 2;
50 dr1["questionContent"] = "q2";
51 dr1.SetParentRow(dr);
52 ds.Tables["Question"].Rows.Add(dr1);
53
54 dr2 = ds.Tables["Possible_Answer"].NewRow();
55 dr2["answerIndex"] = 1;
56 dr2["answerContent"] = "a21";
57 dr2.SetParentRow(dr1);
58 ds.Tables["Possible_Answer"].Rows.Add(dr2);
59
60 dr2 = ds.Tables["Possible_Answer"].NewRow();
61 dr2["answerIndex"] = 2;
62 dr2["answerContent"] = "a22";
63 dr2.SetParentRow(dr1);
64 ds.Tables["Possible_Answer"].Rows.Add(dr2);
65
66 myCommand1.Update(ds,"SurveyTemplate");
67 myCommand2.Update(ds, "Question");
68 myCommand3.Update(ds, "Possible_Answer");
69 ds.AcceptChanges();
70

and that causes (at line 67):"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Question_SurveyTemplate". The conflict occurred in database
"ankietyzacja", table "dbo.SurveyTemplate", column
'id'.
The statement has been terminated.
at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
at AnkietyzacjaWebService.Service1.createSurveyTemplate(Object[] o) in J:\PL\PAI\AnkietyzacjaWebService\AnkietyzacjaWebServicece\Service1.asmx.cs:line 397"


Could You please tell me what am I missing here ?
Thanks a lot.
 

View 5 Replies View Related

Interaction Between Instead Of Insert Trigger And Output Clause Of Insert Statement

Jan 14, 2008


This problem is being seen on SQL 2005 SP2 + cumulative update 4

I am currently successfully using the output clause of an insert statement to return the identity values for inserted rows into a table variable

I now need to add an "instead of insert" trigger to the table that is the subject of the insert.

As soon as I add the "instead of insert" trigger, the output clause on the insert statement does not return any data - although the insert completes successfully. As a result I am not able to obtain the identities of the inserted rows

Note that @@identity would return the correct value in the test repro below - but this is not a viable option as the table in question will be merge replicated and @@identity will return the identity value of a replication metadata table rather than the identity of the row inserted into my_table

Note also that in the test repro, the "instead of insert" trigger actually does nothing apart from the default insert, but the real world trigger has additional code.

To run the repro below - select each of the sections below in turn and execute them
1) Create the table
2) Create the trigger
3) Do the insert - note that table variable contains a row with column value zero - it should contain the @@identity value
4) Drop the trigger
5) Re-run the insert from 3) - note that table variable is now correctly populated with the @@identity value in the row

I need the behaviour to be correct when the trigger is present

Any thoughts would be much appreciated

aero1


/************************************************
1) - Create the table
************************************************/
CREATE TABLE [dbo].[my_table](
[my_table_id] [bigint] IDENTITY(1,1) NOT NULL,
[forename] [varchar](100) NULL,
[surname] [varchar](50) NULL,
CONSTRAINT [pk_my_table] PRIMARY KEY NONCLUSTERED
(
[my_table_id] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, FILLFACTOR = 70) ON [PRIMARY]
)

GO
/************************************************
2) - Create the trigger
************************************************/
CREATE TRIGGER [dbo].[trig_my_table__instead_insert] ON [dbo].[my_table]
INSTEAD OF INSERT
AS
BEGIN

INSERT INTO my_table
(
forename,
surname)
SELECT
forename,
surname
FROM inserted

END

/************************************************
3) - Do the insert
************************************************/

DECLARE @my_insert TABLE( my_table_id bigint )

declare @forename VARCHAR(100)
declare @surname VARCHAR(50)

set @forename = N'john'
set @surname = N'smith'

INSERT INTO my_table (
forename
, surname
)
OUTPUT inserted.my_table_id INTO @my_insert
VALUES( @forename
, @surname
)

select @@identity -- expect this value in @my_insert table
select * from @my_insert -- OK value without trigger - zero with trigger

/************************************************
4) - Drop the trigger
************************************************/

drop trigger [dbo].[trig_my_table__instead_insert]
go

/************************************************
5) - Re-run insert from 3)
************************************************/
-- @my_insert now contains row expected with identity of inserted row
-- i.e. OK

View 5 Replies View Related

Case Statement Error In An Insert Statement

May 26, 2006

Hi All,
I've looked through the forum hoping I'm not the only one with this issue but alas, I have found nothing so I'm hoping someone out there will give me some assistance.
My problem is the case statement in my Insert Statement. My overall goal is to insert records from one table to another. But I need to be able to assign a specific value to the incoming data and thought the case statement would be the best way of doing it. I must be doing something wrong but I can't seem to see it.

Here is my code:
Insert into myTblA
(TblA_ID,
mycasefield =
case
when mycasefield = 1 then 99861
when mycasefield = 2 then 99862
when mycasefield = 3 then 99863
when mycasefield = 4 then 99864
when mycasefield = 5 then 99865
when mycasefield = 6 then 99866
when mycasefield = 7 then 99867
when mycasefield = 8 then 99868
when mycasefield = 9 then 99855
when mycasefield = 10 then 99839
end,
alt_min,
alt_max,
longitude,
latitude
(
Select MTB.LocationID
MTB.model_ID
MTB.elevation, --alt min
null, --alt max
MTB.longitude, --longitude
MTB.latitude --latitude
from MyTblB MTB
);

The error I'm getting is:
Incorrect syntax near '='.

I have tried various versions of the case statement based on examples I have found but nothing works.
I would greatly appreciate any assistance with this one. I've been smacking my head against the wall for awhile trying to find a solution.

View 10 Replies View Related

How To Use Select Statement Inside Insert Statement

Oct 20, 2014

In the below code i want to use select statement for getting customer

address1,customeraddress2,customerphone,customercity,customerstate,customercountry,customerfirstname,customerlastname

from customer table.Rest of the things will be as it is in the following code.How do i do this?

INSERT INTO EMImportListing ("
sql += " CustId,Title,Description,JobCity,JobState,JobPostalCode,JobCountry,URL,Requirements, "
sql += " IsDraft,IsFeatured,IsApproved,"
sql += " Email,OrgName,customerAddress1,customerAddress2,customerCity,customerState,customerPostalCode,

[code]....

View 1 Replies View Related

Insert Statement Which Uses A Return Value From An SP As An Insert Value

Jul 20, 2005

I'm quite stuck with this:I have an import table called ReferenceMatchingImport which containsdata that has been sucked from a data submission. The contents ofthis table have to be imported into another table ExternalReferencewhich has various foreign keys.This is simple but one of these keys says that the value inExternalReference.CompanyRef must be in the CompanyReference table.Of course if this is an initial import then it will not be so as partof my script I must insert a new row into CompanyReference andpopulate ExternalReference.CompanyRef with the identity column of thistable.I thought a good idea would be to use an SP which inserts a new rowand returns @@Identity as the value to insert. However this doesn'twork as far as I can tell. Is there a approved way to perform thissort of opperation? My code is below.Thanks.ALTER PROCEDURE SP00ReferenceMatchingImportAS/*Just some integrity checking going on here*/INSERT ExternalReference(ExternalSourceRef,AssetGroupRef,CompanyUnitRef,EntityTypeCode,CompanyRef, --this is the unknown ref which is returned by the spExternalReferenceTypeCode,ExternalReferenceCompanyReferenceMapTypeCode,StartDate,EndDate,LastUpdateBy,LastUpdateDate)SELECT rmi.ExternalDataSourcePropertyRef,rmi.AssetGroup,rmi.CompanyUnit,rmi.EntityType,SP01InsertIPDReference rmi.EntityType, --here I'm trying to run thesp so that I can use the return value as the insert value1,1,GETDATE(),GETDATE(),'RefMatch',GETDATE()FROM ReferenceMatchingImport rmiWHERE rmi.ExternalDataSourcePropertyRef NOT IN (SELECT ExternalSourceRefFROM ExternalReference)

View 3 Replies View Related

INSERT Statement

May 1, 2007

I was wondering if any SQL people out there know if i can INSERT INTO 2 tables at the same time? I havent found a yes to the question so i thought i would throw it out there and see what everyone has to say. word 

View 3 Replies View Related

Need Help With INSERT INTO Statement...

Jan 4, 2008

I have put together the following code, but am getting a syntax error on the Insert Into statement. Could someone kindly tell me what I am doing wrong? Thanks  1 Protected Sub SubmitButton2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton2.Click2 authAndSaveToDB()3 End Sub4 Private Sub authAndSaveToDB()5 On Error GoTo errhand6 If connectToDB() Then 'connection to database was successful7 'insert candidate in the database
8 insertCandidate(ddlPositions.Text, txtName.Text, txtBio.Text, conn)9 Response.Redirect("FileUpload.aspx")10
11 Else
12 Response.Write("<font color = red><strong>Database connection failure. Please try again in a few minutes or contact system administrator.</strong></font>")13 End If
14 closeDB() 'end the connection to the database
15 Exit Sub
16 errhand:17 Response.Write("<br>ERROR: " & Err.Description & "<br>")18 End Sub19 Private Sub insertCandidate(ByVal strPositions As String, ByVal strCandidate As String, ByVal strBiography As String, ByVal myconn As OleDb.OleDbConnection)20 Dim cmd As OleDb.OleDbCommand21 Dim strSQL As String
22
23 strSQL = "INSERT INTO Position (Positions,Candidate,Biography) VALUES ('" & _
24 strPositions & "'," & _
25 "'" & strCandidate & "'," & _
26 "'" & strBiography & "')"
27 cmd = New OleDb.OleDbCommand(strSQL, myconn)28 cmd.ExecuteNonQuery()29 End Sub30 End Class
  

View 16 Replies View Related

Insert SQL Statement

Jan 31, 2008

Hi, I am retriving the value time from my database and i have the convert function on it CONVERT (varchar, Time, 8)
When i edit this and try and insert it back to the database i am losing the information. I am not sure how the insert statement shoulld read in order to do this.
Thanks Mike

View 8 Replies View Related

SQL Insert Statement

Feb 14, 2008

Hi forum, currently I insert a mobile phone number into colomn OK but what I need to do is add +61 as a prefix.Users provide 055 555 555, I want to store number as +61 55 555 555 (note this also drops the 0) my SQL skills a little lacking so appreciate all good info, cheers P

View 2 Replies View Related

Insert Statement

Apr 3, 2004

Hi Everyone

I am having difficulties with my first hand coded insert statement. The record inserts BUT the first item VALUE is selected for all the drop down lists ( 3 of them are optional) I have Prerenders on the page to insert a null value at the top of the list. For the dropdown that is mandatory it only enter first item. Thats without specifying type. As soon as I specify type I get - Input string not in correct format - doesn't actually tell me which one!!!!!! All char types match the database.

Here is my insert:



Sub Add_Click(sender as object, e as EventArgs)

Dim conBooks As SqlConnection
Dim strInsert As String
Dim cmdInsert As SqlCommand

conBooks = New SqlConnection( System.Configuration.ConfigurationSettings.AppSettings("conFantasy") )
strInsert = "INSERT INTO dbo.Books (ISBN, BookTitle, AuthorID, AuthorType, author2, author3, Series, VolNo, Synopsis, PubYear, PubDate) VALUES (@ISBN, @BookTitle, @AuthorID, @AuthorType, @author2, @author3, @Series, @VolNo, @Synopsis, @PubYear, @PubDate )"

cmdInsert = New SqlCommand( strInsert, conBooks )

' Add Parameters
cmdInsert.Parameters.Add( "@ISBN", SqlDbType.nvarchar).Value = txtISBN.Text
cmdInsert.Parameters.Add( "@BookTitle", SqlDbType.nvarchar).Value = title.Text
cmdInsert.Parameters.Add( "@AuthorID", SqlDbType.int).Value = AuthorID.SelectedItem.Value
cmdInsert.Parameters.Add( "@AuthorType", SqlDbType.char).Value = AuthorType.SelectedItem.Value
cmdInsert.Parameters.Add( "@author2", SqlDbType.int).Value = author2.SelectedItem.Value
cmdInsert.Parameters.Add( "@author3", SqlDbType.int).Value = Author3.SelectedItem.Value
cmdInsert.Parameters.Add( "@Series", SqlDbType.nvarchar).Value = Series.SelectedItem.Value
cmdInsert.Parameters.Add( "@VolNo", SqlDbType.int).Value = volumeno.Text
cmdInsert.Parameters.Add( "@Synopsis", SqlDbType.ntext).Value = txtSynopsis.Text
cmdInsert.Parameters.Add( "@PubYear", SqlDbType.bigint).Value = pubyear.Text
cmdInsert.Parameters.Add( "@PubDate", SqlDbType.nvarchar).Value = PubDate.Text


conBooks.Open()
cmdInsert.ExecuteNonQuery()
conBooks.Close()

Response.Redirect("/admin/default.aspx")
End Sub

View 4 Replies View Related

Insert Statement...

Feb 13, 2006

Hi All,
I am trying to insert data into table1 by getting data from table2, table3 and looking whether the data is already not exist in table1.
Here is my code...
insert into table1 (first_name, last_name, user_login, email, organization_name) values (select ru.firstname, ru.lastname, ru.UserID, ru.EmailAddress, ru.BusinessName from table2 ru, table3  wepsUsers where ru.id = wepsUsers.user_id and not exists  (select user_login from table1  where user_login = ru.UserID))
 
When I excute the code, I am getting the following error.....
Server: Msg 156, Level 15, State 1, Line 3Incorrect syntax near the keyword 'select'.Server: Msg 170, Level 15, State 1, Line 7Line 7: Incorrect syntax near ')'.
But, If execute the following code....
select ru.firstname, ru.lastname, ru.UserID, ru.EmailAddress, ru.BusinessName from table2 ru, table3  wepsUsers where ru.id = wepsUsers.user_id and not exists  (select user_login from table1  where user_login = ru.UserID).... I am able to see the values.
 
Can any one shade on my code? and please let me know, where I am doing wrong. I am appreciate your help.
 
Thanks.
Srinivas.

View 3 Replies View Related

Insert Into Statement

Mar 27, 2001

Hi, Every body,

Is there anyway that we can use insert into statement to insert data into the first row of a table, or initialize the column with the new inserted data.

Thanks in Advance,

View 4 Replies View Related

Insert Statement

Nov 2, 2000

I am trying to do an insert in a particular View...one of the field has got an 'Apostrophe'.(Ex: SQl Server's).
When i do this i get an error. the system does not allow me to insert....
is there any way i can do an Insert with that...???

Thanks

View 2 Replies View Related

Insert Statement

Feb 2, 2001

How can you insert this statement in a table using Query Analyzer.
(today's date)as single statement.


Thank You,
John

View 1 Replies View Related

Insert Statement

Nov 17, 2005

How do I
1.) take two seperate columns and combine the data
2.) take that combined data and populate a third column.

Here is an example of what I've been trying to do:

Insert INTO Table_1 (Column1)
Select Column2 + Column3
From Table_1

I continue to get this error message:

Server: Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'Column_2', table 'DB1.dbo.Table_1'; column does not allow nulls. INSERT fails.
The statement has been terminated.

If some one could please give me a general script that could do this I would appreciate it. I'm new to using SQL and I'm a little bit lost.

Thanks.

View 4 Replies View Related

Need Help With My Insert Statement

Sep 29, 2004

I need an insert statement that will grab the maximum of TimeGenerated from the Events table and insert it into LastEventTime in the Host Table. But it has to be inserted based on the relationship of SystemNetName.

For Example,

Host Table
--------------------------------------
SystemNetName LastEventTime
Tweety 9/24/2004
Sylvester 9/25/2004

Events Table
----------------------------------------
SystemNetName TimeGenerated
Tweety 9/24/2004
Tweety 8/26/2004
Sylvester 8/21/2004
Sylvester 9/25/2004
Sylvester 7/5/2004


This is what I had so far but didn't work:
Insert into host(LastEventTime)
Select(Max(TimeGenerated) ) from Events Where
Events.SystemNetName = Host.SystemNetName


Any Ideas?

View 5 Replies View Related

Using Where In A Insert Statement

Aug 20, 2004

Is is possible to use a Where Clause in a Insert statement in MS SQL? I keep getting a syntax error near 'Where'. Is there something wrong with this?

Insert INTO CPU (CPUNumber, Name, MaxClockSpeed, SystemNetName) Values('CPU2', 'Intel', '2392', 'TWEETY') Where 'CPU2' NOT IN (Select CPUNumber from CPU)

I want to insert into the cpu table as long as what I am inserting is not already in the table.

Desparate.

Thanks,
Laura

View 3 Replies View Related

Chr(10) In An Insert Statement.

Jun 22, 2004

Can someone help me parse this oracle insert statement into SQL Server please?

insert into notify_template (subject, body, priority)
values
(
'
Budgeted time exceeded for task [18040]
',
'
Actual Time exceeds Budgeted time for the following task'
|| chr(10) || chr(10) ||
'Task Name : [18040]
Root Program Name : [18049]
Actual Days : [2000000100]
Budgeted Days : [2000000101]
Estimated Time : [2000000102]'
|| chr(10) || chr(10) ||
' The following resource(s) in the above task have exceeded the budgeted time:'
|| chr(10) || chr(10) ||
' [2000000784]'
|| chr(10) || chr(10) ||
'Click here : [12865]
',
2)

View 1 Replies View Related

Insert Statement Help

Jul 16, 2006

hi all

i am writing a trigger that inserts from one table to the next. i have an issue with the table being inserted into have 2 more columns than the one being inserted from. Here is the trigger just in case

CREATE TRIGGER [Insert40801] ON [dbo].[tPA10801]
FOR INSERT

AS

insert into tPA40801
select
intTimesheetKey,
chrTimesheetNumber,
TranID,
intEmployeeKey,
intEmployeeDivKey,
BatchKey,
dtePeriodStartDate,
dtePeriodEndDate,
chrStatus1,
numTotalHrsWorked,
numTotalHrsBilled,
numTotalCosts,
numTotalCharges,
numTotalRecover,
chrSignedID,
dteSignedDate,
chrApprovalID,
dteApprovalDate,
intJobKey,
intPhaseKey,
intTaskKey,
dteDate,
siCstClsificatnDDL,
UpdateCounter,
CompanyID



from tpa10801

now tpa40801 has two extra columns that tpa10801 doesnt. how would i please the sql gods and get the insert statement running? thanks alot

tibor

View 2 Replies View Related

Insert Statement Help

Sep 22, 2006

I need to insert over 600 similar records in a table. The only way I know is to write insert into <table> command 600 times. Is there another way which is easier?

Thanks in advance,
Saurav

View 13 Replies View Related

Insert Statement

Mar 25, 2007

my insert statement got no error but when i check my table the values were not inserted actually.. what maybe the problem?

View 12 Replies View Related







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