SQL Insert Statement Error That I Cannot Figure Out

Dec 11, 2004

I am receiving the following error when trying to insert values from textboxes on a registration form:





Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.





Compiler Error Message: BC30205: End of statement expected.





Source Error:











Line 19: Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)


Line 20:


Line 21: Dim queryString As String = "INSERT INTO [UserID_db] ([Code], [UserID], [Password], [Email1], [Name_First], [Name_Last], [Admin_level]) VALUES ('" & txtUserID.Text"', '" & txtUserID.Text"', '" & txtPassword.Text"', '" & txtEmail1.Text"', '" & txtFirstName"', '" & txtLastName.Text"', '" & txtAdminLevel.Text"')"


Line 22: Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand


Line 23: dbCommand.CommandText = queryString








My code is below. Can anyone help me figure out what is wrong with my code?





<%@ Page Language="VB" Debug="true" %>


<%@ Register TagPrefix="wmx" Namespace="Microsoft.Matrix.Framework.Web.UI" Assembly="Microsoft.Matrix.Framework, Version=0.6.0.0, Culture=neutral, PublicKeyToken=6f763c9966660626" %>


<%@ import Namespace="System.Data" %>


<%@ import Namespace="System.Data.OleDb" %>


<script runat="server">





Sub btnSubmit_Click(sender As Object, e As EventArgs)





Dim UCde as string = txtUserID.Text


Dim UserID as string = txtUserID.Text


Dim Password as string = txtPassword.Text


Dim Email1 as string = txtEmail.Text


Dim FirstName as string = txtFirstName.Text


Dim LastName as string = txtLastName.Text


Dim AdminLevel as string = dropAccountType.SelectedItem.Value








Dim connectionString As String = "server='(local)'; trusted_connection=true; database='master'"


Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)





Dim queryString As String = "INSERT INTO [UserID_db] ([Code], [UserID], [Password], [Email1], [Name_First], [Name_Last], [Admin_level]) VALUES ('" & txtUserID.Text"', '" & txtUserID.Text"', '" & txtPassword.Text"', '" & txtEmail1.Text"', '" & txtFirstName"', '" & txtLastName.Text"', '" & txtAdminLevel.Text"')"


Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand


dbCommand.CommandText = queryString


dbCommand.Connection = dbConnection





Dim rowsAffected As Integer = 0


dbConnection.Open()


dbCommand.ExecuteNonQuery()


dbConnection.Close()


End Sub








Thanks for your help.





Chris

View 5 Replies


ADVERTISEMENT

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

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

Real Figure Instead Of Exponential Figure Needed

May 29, 2008

Hello,

I use OPENROWSET to read values from Excel and store them in a SQL Server table. In the Excel file I have a row having format 'Number' with two decimal places.

Example: 1225000.00

When I select this value using SSMS I get the correct value:

1225000

Strange enough, I cannot see the decimals anymore. However, when I now store this value into my table and then select it from there I get: (the datatype in the table is VARCHAR(max))

1.225e+006

I would not care if I could convert this back to a numeric datatype but this seems not to work: CAST('1.225e+006' as INT) throws an exception. Obviously OPENROWSET sends the data strictly as a character string. Storing this into varchar(max) works for small figures but it starts to use exp values for big figures.

Does anybody has an idea how to bring huge Excel based figures safely into a MS SQL Table ?

Thanks: Peter

View 5 Replies View Related

Including MTD And YTD Figure With A Daily Figure

Feb 4, 2008

Hello,
I have a query that returns a daily revenue figure. The query is as follows:

SELECT top 1000
ds.AcctCode,
ds.TxnDate,
SUM(isnull(ds.FuelFee,0)) + SUM(isnull(ds.CashFee,0)) + SUM(isnull(ds.ScFee,0)) AS TotalDailyRevenue,
--"MTD" = ?,
--"YDT" = ?,
ps.TC,
CASE
WHEN ps.Proj = 100 THEN 'New Account'
WHEN ps.Proj = 200 THEN 'Current Account'
END AS ProjStatus,
ps.FSR,
ps.SubmitRep1

FROM
TxnRptg.dbo.tbl_DailySummary ds
INNER JOIN SalesData.dbo.tbl_CYProcessedSales ps
ON ds.AcctCode = ps.Acct

WHERE
MONTH(ds.TxnDate) = 1
AND
Proj IN (100,200)
AND TC = 'HV'

GROUP BY
ds.AcctCode, ds.TxnDate, ps.TC, ps.Proj, ps.FSR, ps.SubmitRep1

ORDER BY
ds.AcctCode, ds.TxnDate

--*********************************

TxnDate represents a single day of the month. How can I include MTD so that the dates for the revenue total are from DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) (beginning of current month) to TxnDate, and YTD so that the revenue totals are from DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) (beginning of the current year) to TxnDate?


Thank you for your help!


cdun2

View 5 Replies View Related

Can't Figure Out This Error!

Jun 8, 2007

Here is my code below. When I attempt to run the data flow task that calls this script, I get this error:



"Index was outside the bounds of the array."



I honestly do not know what the problem is here. There are definitely 6 columns in the file. In fact, even if comment out everything except the first line (myCol1), I still get the "Index was outside the bounds of the array." error.



Any ideas??? Need help.



Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

Dim rowValues As String()

rowValues = Row.Line.Split(columnDelimiter) 'parse row by comma

If Row.Line Like "*OPENING BALANCE*" Then

Row.AccountNumber = Nothing 'set to null for conditional split

Row.OpeningBalance = CDec(rowValues(3)) 'get the 4th value



ElseIf Row.Line Like "*CLOSING BALANCE*" Then

Row.AccountNumber = Nothing 'set to null for conditional split

Row.ClosingBalance = CDec(rowValues(2)) 'get the 3rd value



Else

Row.myCol1 = CStr(rowValues(0)).Replace("""", String.Empty)

Row.myCol2 = CStr(rowValues(1)).Replace("""", String.Empty)

Row.myCol3 = CStr(rowValues(2)).Replace("""", String.Empty)

Row.myCol4 = CStr(rowValues(3)).Replace("""", String.Empty)

Row.myCol5 = CStr(rowValues(4)).Replace("""", String.Empty)

Row.myCol6 = CDec(rowValues(5))



End If

End Sub

View 10 Replies View Related

Can't Figure Out Error Message In SQL

Oct 16, 2007

Can someone please look at my stored procedure? I am trying to create the following stored procedure, but get the following errormessages:
Msg 102, Level 15, State 1, Procedure InsertWork, Line 3Incorrect syntax near '7'.Msg 102, Level 15, State 1, Procedure InsertWork, Line 25Incorrect syntax near '@7am8am'.
USE [Work]GO
SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[InsertWork](  7am8am       nvarchar(500),  8am9am       nvarchar(500),  9am10am       nvarchar(500),  10am11am      nvarchar(500),                  11am12noon    nvarchar(500),                12Noon1pm     nvarchar(500),  1pm2pm       nvarchar(500),  2pm3pm       nvarchar(500),  3pm4pm        nvarchar(500),  4pm5pm       nvarchar(500),                  5pm6pm       nvarchar(500),  6pm7pm       nvarchar(500),  7pm8pm       nvarchar(500),  8pm9pm        nvarchar(500),  9pm10pm       nvarchar(500),                  10pm11pm      nvarchar(500),  Notes         nvarchar(500),         Date           nvarchar(15))AS BEGIN INSERT INTO WorkDay VALUES                 @7am8am,                 @8am9am,  @9am10am,   @10am11am,   @11am12Noon,  @12Noon1pm,  @1pm2pm,  @2pm3pm,  @3pm4pm,  @4pm5pm,  @5pm6pm,  @6pm7pm,  @7pm8pm,   @8pm9pm,  @9pm10pm,  @10pm11pm,  @Notes,  @DateEND
 

View 3 Replies View Related

Need Help To Figure Out This SqlQueryNotificationService Error.

Mar 30, 2008

I found every several minutes, sometimes one or twice in an hour, I still get a dozen error like below logged in SQL Log. See the error is "You do not have permission to access the service". I found some articles on other errors, but nothing about this error. I want to get more information on this, and a way to trace what is the permission about and which user doesn't have the permission.


Source spid26s

Message
The query notification dialog on conversation handle '{E6FC299F-8BFE-DC11-A4E1-000D5670268E}.' closed due to the following error: '<?xml version="1.0"?><Error xmlns="http://schemas.microsoft.com/SQL/ServiceBroker/Error"><Code>-8494</Code><Description>You do not have permission to access the service &apos;SqlQueryNotificationService-9ff8b39d-90a8-45bc-83a7-23837920774d&apos;.</Description></Error>'.



thanks

View 7 Replies View Related

Insert Statement Error

Apr 8, 2005

Hi All,

I am trying to run an insert statement and getting an error.

Insert statement:

insert into conv_owner (name,street_num,
street_direction,street_name,street_type,street_un it,
address2,city,state,city_state,zip,wphone,inservic e,
db_name,table_name)
select "Facility's Owner",null,null,null,null,null,null,null,
null,null,null,"Owner's Telephone Number",inservice,
'BKFoodProtection.mdb','FP_Master'
from fp_master

Error message:
Server: Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.

Any idea why? Thanks.

View 6 Replies View Related

Error In Insert Statement ........Help Out

May 13, 2008

Hi
All as i have a class where i wrote a procedure for insert statement and i passed the value from the form and previously it was fine and now its giving the following error

" The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.The statement has been terminated."

And
code is as follows




Code Snippet

Public Sub Purchase_Header(ByVal BillNo As VariantType, ByVal BillDate As Date, ByVal GRNNO As VariantType, ByVal GRNdate As Date, ByVal TOP As Integer, ByVal Supplier As Integer, ByVal TotalPurchasevalue As Double, ByVal TotalProductValue As Double, ByVal BillPaid As Date, ByVal BillDue As Date, ByVal NoOfSBills As Integer, ByVal noofbreceived As Integer, ByVal billstatus As Integer, ByVal paymentstatus As Integer, ByVal appstatus As Integer, ByVal recitstatus As Boolean, ByVal sbillstatus As Boolean, ByVal ccindicator As String)

connection()
myCommand = New SqlCommand("INSERT INTO Purchase_Header(PH_Voucher_Date,PH_Bill_No,PH_Bill_Date,PH_GRN_No,PH_GRN_Date,PH_Type_Of_Purchase_Id,PH_Supplier_Id,PH_Total_Purchase_Value,PH_Total_Product_Value,PH_Bill_Paid_On,PH_Bill_Due_On,PH_No_Of_Sub_Bills,PH_No_Of_Sub_Bills_Received,PH_Bill_Status,PH_Payment_Status,PH_Apportionment_Status,PH_Goods_Receipt_Status,PH_Sub_Bill_Receipt_Status,PH_Cash_Credit_Indicator,PH_Total_Tax_Paid) VALUES('" & System.DateTime.Today & "'," & BillNo & ",'" & BillDate & "'," & GRNNO & ",'" & GRNdate & "'," & TOP & "," & Supplier & "," & TotalPurchasevalue & "," & TotalProductValue & ",'" & BillPaid & "','" & BillDue & "'," & NoOfSBills & "," & noofbreceived & "," & billstatus & "," & paymentstatus & "," & appstatus & ",'" & recitstatus & "','" & sbillstatus & "' ,'" & ccindicator & "',0)", myConnection)
myCommand.ExecuteReader()

MsgBox("Data saved successfully")
myConnection.Close()
and table structure is as follows and for date types i am passing them through date variables from textbox

INSERT INTO [MoneyBee].[dbo].[Purchase_Header]
([PH_Voucher_Date]
,[PH_Bill_No]
,[PH_Bill_Date]
,[PH_GRN_No]
,[PH_GRN_Date]
,[PH_Type_Of_Purchase_Id]
,[PH_Supplier_Id]
,[PH_Total_Purchase_Value]
,[PH_Total_Product_Value]
,[PH_Bill_Paid_On]
,[PH_Bill_Due_On]
,[PH_No_Of_Sub_Bills]
,[PH_No_Of_Sub_Bills_Received]
,[PH_Bill_Status]
,[PH_Payment_Status]
,[PH_Apportionment_Status]
,[PH_Goods_Receipt_Status]
,[PH_Sub_Bill_Receipt_Status]
,[PH_Cash_Credit_Indicator]
,[PH_Total_Tax_Paid])
VALUES
(<PH_Voucher_Date, datetime,>
,<PH_Bill_No, varchar(15),>
,<PH_Bill_Date, datetime,>
,<PH_GRN_No, numeric,>
,<PH_GRN_Date, datetime,>
,<PH_Type_Of_Purchase_Id, numeric,>
,<PH_Supplier_Id, numeric,>
,<PH_Total_Purchase_Value, numeric,>
,<PH_Total_Product_Value, numeric,>
,<PH_Bill_Paid_On, datetime,>
,<PH_Bill_Due_On, datetime,>
,<PH_No_Of_Sub_Bills, numeric,>
,<PH_No_Of_Sub_Bills_Received, numeric,>
,<PH_Bill_Status, numeric,>
,<PH_Payment_Status, numeric,>
,<PH_Apportionment_Status, numeric,>
,<PH_Goods_Receipt_Status, bit,>
,<PH_Sub_Bill_Receipt_Status, bit,>
,<PH_Cash_Credit_Indicator, varchar(6),>
,<PH_Total_Tax_Paid, numeric,>)

Thanks
Avinash

View 5 Replies View Related

Error:: The Insert Statement ...

Apr 26, 2008

hi

i'm having a problem with my project we need to make for school with asp.net & c#. the problem is i'm a newbie with c#.
the project we need to make is a survey. so the problem is my first question of the survey works fine when i push the go to next it enters the data nice into my sql db and my second question loads, then I enter the answer for my second question i press go to next question and i get this error: " The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Antwoorden_Gebruikers". The conflict occurred in database "GIP_enquete", table "dbo.Gebruikers", column 'Gebruiker_ID'. " I don't know how i can fix this cause im to newbie to understand whats wrong.




here is a view of my code:





Code Snippet

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using enqueteTableAdapters;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int Vraag_ID = Convert.ToInt16(Request.QueryString["vraagid"]);
VragenTableAdapter VraagAdapter = new VragenTableAdapter();
lblVraag.Text = Convert.ToString(VraagAdapter.GeefVraag(Vraag_ID));

if (Vraag_ID == 1)
{
pnlVraag1.Visible = true;
}

if (Vraag_ID == 2)
{
pnlVraag2.Visible = true;
}

}
protected void btnVraag1_Click(object sender, EventArgs e)
{
//make a new user
GebruikersTableAdapter GebruikerAdapter = new GebruikersTableAdapter();
DateTime Moment = System.DateTime.Now;
GebruikerAdapter.GebruikerToevoegen(Moment);
int GebruikerID = Convert.ToInt16(GebruikerAdapter.GeefGebruikerID(Moment));
this.ViewState.Add("gebruiker_id", GebruikerID);

//send answer
AntwoordenTableAdapter AntwoordAdapter = new AntwoordenTableAdapter();
AntwoordAdapter.AntwoordIngeven(1, GebruikerID, txtVraag1.Text, null);

//go to 2nd question
Response.Redirect("Default.aspx?vraagid=2", true);
}

protected void btnVraag2_Click(object sender, EventArgs e)
{
//get back the user from question 1
int GebruikerID = Convert.ToInt16(this.ViewState["gebruiker_id"]);


//send answer
AntwoordenTableAdapter AntwoordAdapter = new AntwoordenTableAdapter();
AntwoordAdapter.AntwoordIngeven(2, GebruikerID, txtVraag2.Text, null);


when i run debug it allways stops here





//go too 3th question
Response.Redirect("Default.aspx?vraagid=3", true);
}
}

can somebody plz help me ? =(

ps: sorry for my bad english

View 3 Replies View Related

Is There A Size Limit To This Cause Im Getting An Error That I Cant Figure Out

Mar 14, 2006

I create an sql string as so, add parameters to it and execute it:
string cmdstr = "INSERT INTO locations(id1, id2, companyname, address, city, province, postalcode, phonenumber, faxnumber, contact, contactemail) VALUES (@id1,@id2,@companyname,@address,@city,@province,@postalcode,@phonenumber,@faxnumber,@contact,@contactemail)";
SqlCommand sqlCmd = GetCommandSQL(cmdstr);
sqlCmd.CommandTimeout = TimeOut;
sqlCmd.Parameters.Add("@id1", SqlDbType.Int).Value = itID;
sqlCmd.Parameters.Add("@id2", SqlDbType.Int).Value = Convert.ToInt32(ddlDPCLocation.SelectedValue);
sqlCmd.Parameters.Add("@companyname", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbCompanyName")).Text;
sqlCmd.Parameters.Add("@address", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbAddress")).Text;
sqlCmd.Parameters.Add("@city", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbCity")).Text;
sqlCmd.Parameters.Add("@province", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbProvince")).Text;
sqlCmd.Parameters.Add("@postalcode", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbPostalCode")).Text;
sqlCmd.Parameters.Add("@phonenumber", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbPhoneNumber")).Text;
sqlCmd.Parameters.Add("@faxnumber", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbFaxNumber")).Text;
sqlCmd.Parameters.Add("@contact", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbContact")).Text;
sqlCmd.Parameters.Add("@contactemail", SqlDbType.VarChar).Value = ((TextBox)dvShippingInformation.FindControl("tbContactEmail")).Text;
sqlCmd.ExecuteNonQuery();
for testing purposes ive added the max text in each textbox area, so each textbox has 50 characters or so
and i get an error message as follows, when executing the query:
"System.Data.SqlClient.SqlException: String or binary data would be truncated.
The statement has been terminated.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at _default.InsertGKShippingLocation() in c:\Inetpub\wwwroot\cleanapp\default.aspx.cs:line 125
   at _default.InsertOrder() in c:\Inetpub\wwwroot\cleanapp\default.aspx.cs:line 93
   at _default.InsertandSend() in c:\Inetpub\wwwroot\cleanapp\default.aspx.cs:line 178"
Anybody have any ideas why this is happening

View 1 Replies View Related

Lookup Error How To Figure Out What's Wrong

Mar 19, 2008

I'm new to the SSIS world and am writing my first package. What the package is supposed to do is to take the XML export from one database and import into an identical database (production). There's no connection between the two DBs. During import, the SSIS package checks if there's any primary key values in a table already exist in the production DB and only imports the new records.

So here's the data flow of my package: XML Source -> Lookup -> Conditional Split -> SQL Server Destination. I'm doing a lookup against the same destination DB to check if a record (primary key value) already exists or not, and doing the condition ISNULL(id_out) in the Conditional Split. I really don't know if this is the correct way to implement it. The Lookup control errors out during debugging in Visual Studio. Here's what;s on the progress tab:

[Lookup [1745]] Error: The "component "Lookup" (1745)" failed because error code 0xC020901E occurred, and the error row disposition on "output "Lookup Output" (1747)" specifies failure on error. An error occurred on the specified object of the specified component.

[DTS.Pipeline] Error: The ProcessInput method on component "Lookup" (1745) failed with error code 0xC0209029. The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.

How do I get more specific error on what went wrong?


Thanks
Bob

View 3 Replies View Related

Syntax Error On Insert Statement

Jan 11, 2007

Ok, the following four lines are four lines of code that I'm running, I'll post the code and then explain my issue:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sqlCommand = New SQLCommand("INSERT INTO Bulk (Bulk_Run, Bulk_Totes, Bulk_Drums, Bulk_Boxes, Bulk_Bags, Bulk_Bins, Bulk_Crates) VALUES (" &amp; RunList(x,0) &amp; ", " &amp; Totes &amp; ", " &amp; Drums &amp; ", " &amp; Boxes &amp; ", " &amp; Bags &amp; ", " &amp; Bins &amp; ", " &amp; Crates &amp; ")", Connection)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sqlCommand.ExecuteNonQuery()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sqlCommand = New SQLCommand("INSERT INTO Presort (Presort_Run, Presort_Totes, Presort_Drums, Presort_Boxes, Presort_Bags, Presort_Bins, Presort_Crates) VALUES (" &amp; RunList(x,0) &amp; ", " &amp; Totes &amp; ", " &amp; Drums &amp; ", " &amp; Boxes &amp; ", " &amp; Bags &amp; ", " &amp; Bins &amp; ", " &amp; Crates &amp; ")", Connection)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sqlCommand.ExecuteNonQuery()
The two tables (Bulk & Presort) are <b>exactly</b> the same.  This includes columns, primary keys, IDs, and even permissions.  If I run the last two liens (the INSERT INTO Presort) then it works fine without error.  But whenever I run the first two lines (the INSERT INTO Bulk) I get the following error:
Incorrect syntax near the keyword 'Bulk'.
Anyone have any ideas, thanks

View 2 Replies View Related

Syntax Error On INSERT Statement

Dec 16, 2005

Here is my insert statement:  StringBuilder sb = new StringBuilder();            sb.Append("INSERT INTO patients_import_test ");        sb.Append("(Referral_Number,Referral_Date,FullName,Patient_ien,DOB,FMP,SSN_LastFour,Race_Id,PCM,Age) ");            sb.Append("VALUES(@rnum,@rdate,@fname,@patid,@birthDate,@fmp,@ssan,@race,@pcm,@age) ");            sb.Append("WHERE Referral_Number NOT IN ( SELECT Referral_Number FROM patients_import_test )");I'm getting an "Incorrect syntax near the keyword 'WHERE'".If I remove the WHERE clause the INSERT statement work fine.

View 3 Replies View Related

Error In Insert Into Statement Access

Jan 14, 2013

Using Access 2010 and SQL Server 2012..i added a database through SSMS and added a table named tblEmployee (dbo.tblEmployee)

The table has 3 fields
LName (nvarchar(50), null)
FName (nvarchar(50), null)
Code (nvarchar(50), null)

The access table has 3 fields
FName, text
LName, text
Code, text

I found a code snippet here to insert from the Access table to the SQL table.UtterAccess Discussion Forums > Appending Access table to SQL Server table (and vice-versa) usin...The code is generating this error

Run-time error '3134':
Syntax error in INSERT INTO statement

Code:
Option Compare Database
Sub AppToSQL()
Dim strODBCConnect As String
Dim strSQL As String
'Code from:

[code]...

View 5 Replies View Related

Insert Into Statement Syntax Error

May 30, 2006

Hi,

I have a problem as shown below


Server Error in '/ys(Do Not Remove!!!)' Application.


Syntax error in INSERT INTO statement.

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.OleDb.OleDbException: Syntax error in INSERT INTO statement.

Source Error:





Line 8: <Script runat="server">
Line 9: Private Sub InsertAuthorized(ByVal Source As Object, ByVal e As EventArgs)
Line 10: SqlDataSource1.Insert()
Line 11: End Sub ' InsertAuthorized
Line 12: </Script>
Source File: C:Documents and SettingsDream_AchieverDesktopys(Do Not Remove!!!)Authorizing.aspx Line: 10

Stack Trace:





[OleDbException (0x80040e14): Syntax error in INSERT INTO statement.]
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +177
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +194
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +56
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +105
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +88
System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation) +392
System.Web.UI.WebControls.SqlDataSourceView.ExecuteInsert(IDictionary values) +410
System.Web.UI.WebControls.SqlDataSource.Insert() +13
ASP.authorizing_aspx.InsertAuthorized(Object Source, EventArgs e) in C:Documents and SettingsDream_AchieverDesktopys(Do Not Remove!!!)Authorizing.aspx:10
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +75
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +97
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4919




And part of my program is as shown

<Script runat="server">

Private Sub InsertAuthorized(ByVal Source As Object, ByVal e As EventArgs)

SqlDataSource1.Insert()

End Sub ' InsertAuthorized

</Script>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DIP1ConnectionString %>" ProviderName="<%$ ConnectionStrings:DIP1ConnectionString.ProviderName %>"

InsertCommand="Insert Into Authorize (Army ID,Tag No,Vehicle ID,Vehicle Type,Prescribed Route,Start Time, End Time) VALUES (@ArmyID, @TagNo, @VehicleID, @VehicleType, @PrescribedRoute, @StartTime, @EndTime)">

<insertparameters>

<asp:formparameter name="ArmyID" formfield="ArmyID" />

<asp:formparameter name="TagNo" formfield="TagNo" />

<asp:formparameter name="VehicleID" formfield="VehicleID" />

<asp:formparameter name="VehicleType" formfield="VehicleType" />

<asp:formparameter name="PrescribedRoute" formfield="PrescribedRoute" />

<asp:formparameter name="StartTime" formfield="StartTime" />

<asp:formparameter name="EndTime" formfield="EndTime" />

</insertparameters>

</asp:SqlDataSource>



Anybody can help? thanks

View 1 Replies View Related

Syntax Error In INSERT INTO Statement.

Apr 7, 2008

Public DBString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Q:VoicenetRTS FolderRTS ChargesAccountscosting.mdb"
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim connstring As New OleDbConnection(DBString)
connstring.Open()
Dim searchstring As String = "SELECT * FROM Costings1"
Dim da As New OleDbDataAdapter(searchstring, connstring)
Dim DS As New DataSet()
Dim dt As DataTable = DS.Tables("Costings1")
da.FillSchema(DS, SchemaType.Source, "Costings1")
da.Fill(DS, "Costings1")
Dim cb As New OleDbCommandBuilder(da)
da.InsertCommand = cb.GetInsertCommand
da.UpdateCommand = cb.GetUpdateCommand
Dim dr As DataRow = DS.Tables("Costings1").NewRow
dr("Key") = TextBox1.Text
dr("CODE") = TextBox2.Text
dr("Element") = TextBox3.Text
etc...
DS.Tables("Costings1").Rows.Add(dr)
da.Update(DS, "Costings1") <<<<<<<<<<<Syntax error in INSERT INTO statement.

There are no spaces in the field names.

View 9 Replies View Related

Error:: The Insert Statement Conflicted With ..

Apr 26, 2008

hi

i'm having a problem with my project we need to make for school with asp.net & c#. the problem is i'm a newbie with c#.
the project we need to make is a survey. so the problem is my first question of the survey works fine when i push the go to next it enters the data nice into my sql db and my second question loads, then I enter the answer for my second question i press go to next question and i get this error: " The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Antwoorden_Gebruikers". The conflict occurred in database "GIP_enquete", table "dbo.Gebruikers", column 'Gebruiker_ID'. " I don't know how i can fix this cause im to newbie to understand whats wrong.




here is a view of my code:





Code Snippet

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using enqueteTableAdapters;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int Vraag_ID = Convert.ToInt16(Request.QueryString["vraagid"]);
VragenTableAdapter VraagAdapter = new VragenTableAdapter();
lblVraag.Text = Convert.ToString(VraagAdapter.GeefVraag(Vraag_ID));

if (Vraag_ID == 1)
{
pnlVraag1.Visible = true;
}

if (Vraag_ID == 2)
{
pnlVraag2.Visible = true;
}

}
protected void btnVraag1_Click(object sender, EventArgs e)
{
//make a new user
GebruikersTableAdapter GebruikerAdapter = new GebruikersTableAdapter();
DateTime Moment = System.DateTime.Now;
GebruikerAdapter.GebruikerToevoegen(Moment);
int GebruikerID = Convert.ToInt16(GebruikerAdapter.GeefGebruikerID(Moment));
this.ViewState.Add("gebruiker_id", GebruikerID);

//send answer
AntwoordenTableAdapter AntwoordAdapter = new AntwoordenTableAdapter();
AntwoordAdapter.AntwoordIngeven(1, GebruikerID, txtVraag1.Text, null);

//go to 2nd question
Response.Redirect("Default.aspx?vraagid=2", true);
}

protected void btnVraag2_Click(object sender, EventArgs e)
{
//get back the user from question 1
int GebruikerID = Convert.ToInt16(this.ViewState["gebruiker_id"]);


//send answer
AntwoordenTableAdapter AntwoordAdapter = new AntwoordenTableAdapter();
AntwoordAdapter.AntwoordIngeven(2, GebruikerID, txtVraag2.Text, null);


when i run debug it allways stops here





//go too 3th question
Response.Redirect("Default.aspx?vraagid=3", true);
}
}

can somebody plz help me ? =(

ps: sorry for my bad english

View 7 Replies View Related

ERROR:- An INSERT EXEC Statement Cannot Be Nested.

May 3, 2004

HI,

WELL WE HAVE BEEN TRYING TO AUTOMATE A PROCEDURE OUT HERE,AND WE ARE TRYING TO CONVERT MOST OF THE THINGS INTO PROCEDURES.

BUT WE ARE GETTING A FEW HICCUPS. PLS HELP

THIS IS HOW IT GOES :-

CREATE PROCEDURE MY_PROC1
AS
BEGIN
ST1 .........;
ST2..........;
END


CREATE PROCEDURE MY_PROC2
AS
BEGIN

CREATE TABLE #TMP2
(COL1 DATATYPE
COL2 DATATYPE)

INSERT INTO #TMP2
EXEC MY_PROC1

ST1 .........;
ST2..........;

END

THIS PROCEDURE TOO RUNS WELL ,AFTER TAKING THE DATA FROM THE FIRST PROC IT MANIPUATES THE DATA ACCORDING TO THE CRITERIA SPECIFIED

NO PROBLEM TILL NOW.......

BUT,

CREATE PROCEDURE MY_PROC3
AS
BEGIN

CREATE TABLE #TMP3
(COL1 DATATYPE
COL2 DATATYPE)

INSERT INTO #TMP3
EXEC MY_PROC2

ST1 .........;
ST2..........;

END

THEN IT GIVES AN ERROR AS :-

"An INSERT EXEC statement cannot be nested."

CAN'T WE , FROM A PROCEDURE CALL A PROCEDURE WHICH CALLS A PROCEDURE........

WHAT IS THE NESTING LEVEL OF A PROCEDURE ?

IS THERE ANY WAY AROUND IT OR CAN IT BE DONE BY CHANGING SOME SETTINGS ?

PLS HELP ME OUT IN THIS

THANKS

View 13 Replies View Related

An INSERT EXEC Statement Cannot Be Nested Error.

Nov 28, 2005

Hi,all,When I use following sql, an error occurs:insert into #tmprepEXECUTE proc_stat @start,@endThere is a "select * from #tmp " in stored procedure proc_stat, and theerror message is :Server: Msg 8164, Level 16, State 1, Procedure proc_stat, Line 42An INSERT EXEC statement cannot be nested.What's the metter? Any help is greatly appreciated. Thanks

View 2 Replies View Related

Error Running Insert Statement In A Database

Aug 15, 2007

When I run this query against PFGDSMRISSQLQ1 in Server manager 2005:use <database>INSERT INTO dbo.<table> (<column1>, <column2>, <column3>)VALUES (12598,2900,1.00)I get this error:Msg 8624, Level 16, State 1, Line 5Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services.Can someone please help. Thanks!

View 1 Replies View Related

SELECT @@IDENTITY During INSERT STATEMENT Error

Mar 9, 2008

The following SQL statement fails on SQL CE 3.5 but works on SQL Express 2005:


"INSERT INTO BOOKINGS VALUES(@now,'"+note+"'," + p + "); SELECT @@IDENTITY;"

Compact 3.5 doesnt like the SELECT statement claiming that:

There was an error parsing the query. [ Token line number = 1,Token line offset = 72,Token in error = SELECT ]


Can anyone suggest the correct SQL to implement this via Compact? i.e. How do I retrieve the Identity value during and insert statement?

I have removed the SELECT @@IDENTITY; portion of the statement and it runs fine.

View 9 Replies View Related

Checkpoint File Falied During Creation - How To Figure This Error Out

Oct 12, 2007

hi folks,

i have this error when trying to run the package in development mode.
and i can not decipher this non-intuitive message:

Error: 0xC001604D at <package name>: Checkpoint file "" failed during creation due to error 0x80070003 "The system cannot find the path specified.".

please note that i have no checkpoints on package anymore; i had two but i deleted them but this message still appears.
i have searched the web but no luck in finding an answer.

maybe someone would be able to point out my obvious mistake here.

many thanks,

Nicolas

View 1 Replies View Related

SQL 2012 :: Select Permission Error On Insert Statement

Jul 28, 2015

Have run to a select permission error when attempting insert data to a table. received the following error

Msg 229, Level 14, State 5, Line 11
The SELECT permission was denied on the object 'tableName', database 'DBname', schema 'Schema'.

Few things to note
- There are no triggers depending on the table
- Permissions are granted at a roll level which is rolled down to the login
- The test environments have the same level of permission which works fine.

View 6 Replies View Related

DTS Table From Access To SQL, Identity Column Error. Should Be Easy, But I Can't Figure It Out.

Oct 4, 2007



I am trying to move data from Access to SQL Server 2000 using DTS.

I have an Access Source and SQL Server Desitination, My destination table has a field called tableID that is not in the source. TableID is a Primary Key and an Identity column.

I have Enable Identity Insert checked in the options of the Transform Data Task.

When I execute ythe task, I get the error

"Cannot insert the value NULL into column 'TableID'. Does not allow nulls. Insert Fails.

Does anyone know why this simple task would fail?

Mike


View 6 Replies View Related

System.Data.OleDb.OleDbException: Syntax Error In INSERT INTO Statement.

May 3, 2007

Hi All I'm having a bit of trouble with an sql statement being inserted into a database - here is the statement:  string sql1;
sql1 = "INSERT into Customer (Title, FirstName, FamilyName, Number, Road, Town,";
sql1 += " Postcode, Phone, DateOfBirth, email, PaymentAcctNo)";
sql1 += " VALUES (";
sql1 += "'" + TxtTitle.Text + "'," ;
sql1 += "'" + TxtForename.Text + "'," ;
sql1 += "'" + TxtSurname.Text + "'," ;
sql1 += "'" + TxtHouseNo.Text + "',";
sql1 += "'" + TxtRoad.Text + "',";
sql1 += "'" + TxtTown.Text + "',";
sql1 += "'" + TxtPostcode.Text + "',";
sql1 += "'" + TxtPhone.Text + "',";
sql1 += "'" + TxtDob.Text + "',";
sql1 += "'" + TxtEmail.Text + "',";
sql1 += "'" + TxtPayAcc.Text + "')"; Which generates a statement like:INSERT into Customer (Title, FirstName, FamilyName,
Number, Road, Town, Postcode, Phone, DateOfBirth, email, PaymentAcctNo) VALUES ('Mr','Test','Test','129','Test Road','Plymouth','PL5
1LL','07855786111','14/04/1930','mr@test.com','123456') I cannot for the life of me figure out what is wrong with this statement. I've ensured all the fields within the database have no validation (this is done within my ASP code) that would stop this statement being inserted. Line 158: dbCommand.Connection = conn;Line 159: conn.Open();Line 160: dbCommand.ExecuteNonQuery();Is the line that brings up the error - I presume this could be either an error in the statement or maybe some settings on the Database stopping the values being added. Any ideas which of this might be ? I'm not looking for someone to solve this for me, just a push in the right direction! Thanks! 

View 2 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

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

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

Error: 0xC002F304 At Bulk Insert Task, Bulk Insert Task: An Error Occurred With The Following Error Message: Cannot Fetch A Row

Apr 8, 2008


I receive the following error message when I try to use the Bulk Insert Task to load BCP data into a table:


Error: 0xC002F304 at Bulk Insert Task, Bulk Insert Task: An error occurred with the following error message: "Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.The bulk load failed. The column is too long in the data file for row 1, column 4. Verify that the field terminator and row terminator are specified correctly.Bulk load data conversion error (overflow) for row 1, column 1 (rowno).".

Task failed: Bulk Insert Task

In SSMS I am able to issue the following command and the data loads into a TableName table with no error messages:
BULK INSERT TableName
FROM 'C:DataDbTableName.bcp'
WITH (DATAFILETYPE='widenative');


What configuration is required for the Bulk Insert Task in SSIS to make the data load? BTW - the TableName.bcp file is bulk copy file as bcp widenative data type. The properties of the Bulk Insert Task are the following:
DataFileType: DTSBulkInsert_DataFileType_WideNative
RowTerminator: {CR}{LF}

Any help getting the bcp file to load would be appreciated. Let me know if you require any other information, thanks for all your help.
Paul

View 1 Replies View Related







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