SqlDataSource1.Insert() Inserts Data Twice

Aug 22, 2006

Hi there,

I'm having a problem where the data taken from the textboxes is being inserted into a table twice. I looked online and someone on another forum was experiencing the same problem. His solution was making the "submitdsabledcontrols" attribute of the form false. That hasn't fixed the issue for me.

Below is my code. I'm still learning all this so this is just a test page, hence the wacky naming conventions.

When the button click calls Button1_Click, all it runs is "SqlDataSource1.Insert()"

Any ideas?

<%@ Page EnableEventValidation="false" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Default3.aspx.vb" Inherits="Default3" title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="mainContent" Runat="Server">

<form id="form1" submitdisabledcontrols=false>

<br />

<asp:Label ID="Label1" runat="server">Name</asp:Label>

<asp:TextBox ID="NameTextBox" runat="server"></asp:TextBox>

<br />

<br />

<asp:Label ID="Label2" runat="server" Text="Label">Number</asp:Label>

<asp:TextBox ID="NumberTextBox" runat="server"></asp:TextBox>

<br />

<br />

<asp:Label ID="Label3" runat="server" Text="Label">Salary</asp:Label>

<asp:TextBox ID="SalaryTextBox" runat="server"></asp:TextBox>&nbsp;

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_click" />

</form>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString1 %>" DeleteCommand="DELETE FROM [Table1] WHERE [TableID] = @original_TableID" InsertCommand="INSERT INTO [Table1] ([Name], [Number], [Salary]) VALUES (@Name, @Number, @Salary)" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [Table1]" UpdateCommand="UPDATE [Table1] SET [Name] = @Name, [Number] = @Number, [Salary] = @Salary WHERE [TableID] = @original_TableID">

<DeleteParameters>

<asp:Parameter Name="original_TableID" Type="Int32" />

</DeleteParameters>

<UpdateParameters>

<asp:Parameter Name="Name" Type="String" />

<asp:Parameter Name="Number" Type="String" />

<asp:Parameter Name="Salary" Type="Decimal" />

<asp:Parameter Name="original_TableID" Type="Int32" />

</UpdateParameters>



<InsertParameters>

<asp:ControlParameter Name="Name" Type="String" ControlID="NameTextBox" />

<asp:ControlParameter Name="Number" Type="String" ControlID="NumberTextBox" />

<asp:ControlParameter Name="Salary" Type="decimal" ControlID="SalaryTextBox" />

</InsertParameters>



</asp:SqlDataSource>

 

</asp:Content>

View 1 Replies


ADVERTISEMENT

SqlDataSource1.insert() Syntax Error!!!

Apr 12, 2007

I am so close to haveing the web page i want, but i hve a syntax error with the Public Function Insert() as Integer.
I see no reason for this
i will post the code below, any help will be appreciated
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" %>
<script runat="server">
Private Sub Submitdata(ByVal Source As Object, ByVal e As EventArgs)
SqlDataSource1.Insert()
End Sub ' Submitdata
</script>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:clientInfoConnectionString %>"
selectcommand="SELECT Client Name,Client Address FROM Clients"
insertcommand="INSERT INTO Clients (Client Name,Client Address) VALUES (@CName,@CAddress)">
<insertparameters>
<asp:formparameter name="CName" formfield="Namebox" />
<asp:formparameter name="CAddress" formfield="Addressbox" />
</insertparameters>
</asp:sqldatasource>
&nbsp;Name:<br />
<asp:TextBox ID="Namebox" runat="server" /><br />
 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="Namebox"
ErrorMessage="Please Enter A Name"></asp:RequiredFieldValidator>
 
<br />Address:<br />
<asp:TextBox ID="Addressbox" runat="server" /><br />
 
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="Addressbox"
ErrorMessage="Please Enter An Address"></asp:RequiredFieldValidator>
 
<br /><asp:Button ID="Submitbtn" runat="server" Text="Submit" OnClick="InsertShipper" />
<br />
 
 
</asp:Content>
Thanks
The King

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

How To Retuen Data With SqlDataSource1.SelectParameters At StoredProcedure

Mar 2, 2007

I Have This StoredProcedure
ALTER PROCEDURE dbo.Default_Edit1
( @ID int, @Family Nvarchar (100) OutPut
)
AS
SELECT @Family=Family FROM Table1 where (ID=@ID)
RETURN
 I went to use  SqlDataSource1.SelectParameters to Return Data
Ho to get and set @ID , @Family with  SelectParameters  ?
 
 
 
 

View 3 Replies View Related

How Do You Insert Into Two Tables From One Insert? Or Even How Would You Using Two Inserts?

Mar 18, 2007

I currently insert into one table with:                 SqlCommand comm = new SqlCommand("INSERT INTO UsersTable (UserName, Password, Email) VALUES (@person, @pass, @email)", sqlConnection);                comm.Parameters.AddWithValue("@person", usrnmeLbl.Text);                comm.Parameters.AddWithValue("@pass", hiddenpassLbl.Text);                comm.Parameters.AddWithValue("@email", hemailLbl.Text);but I realized that there's another table related to this table and I need to have something go in it so that the users data will be recorded at the same pace. So I tried:                 SqlCommand comm = new SqlCommand("INSERT INTO UsersTable, FatherHistTable (UserName, Password, Email), (Father) VALUES (@person, @pass, @email), (@father)", sqlConnection);                comm.Parameters.AddWithValue("@person", usrnmeLbl.Text);                comm.Parameters.AddWithValue("@pass", hiddenpassLbl.Text);                comm.Parameters.AddWithValue("@email", hemailLbl.Text);                comm.Parameters.AddWithValue("@father", fthrsNmeLbl.Text);Not working, so I am thinking I must do two inserts:                  SqlCommand comm = new SqlCommand("INSERT INTO
UsersTable (UserName, Password, Email) VALUES (@person, @pass,
@email)", sqlConnection);
                comm.Parameters.AddWithValue("@person", usrnmeLbl.Text);
                comm.Parameters.AddWithValue("@pass", hiddenpassLbl.Text);
                comm.Parameters.AddWithValue("@email", hemailLbl.Text);                 SqlCommand comm2 = new SqlCommand("INSERT INTO
FatherHistTable (Father) VALUES (@father)", sqlConnection);
                comm2.Parameters.AddWithValue("@father", fthrsNmeLbl.Text); Is that the only way to go about it then? Thanks in advance for any explanations. 

View 26 Replies View Related

BULK INSERT Inserts 2 Rows

May 15, 2008

Greetings

Got bulk insert thing going real nice thanks to your feedback! But now I notice that the BULK INSERT creates 2 identical rows while the flat file has the column headers and then corresponding row, just one row.
Why would it do that. Interestingly if the data file and format file are residing on a shared folder on SQL 2005, and I ran the BULK INSERT from studio it only inserts one row. But when I do BULK INSERT via user interface it creates 2 rows. What is going here.

View 10 Replies View Related

SqlDataSource1.ConnectionString

Jul 4, 2007

This works:
SqlDataSource1.ConnectionString = "Data Source=mydb.myserver.com;Initial Catalog=mydbname;User ID=mydblogin; pwd=mydbpassword";
 This doesn't:
SqlDataSource1.ConnectionString = "<%$ ConnectionStrings:myConnectionString_from_WebConfig %>"
Ok, how do I tell it to use my connection string from my web.config? 

View 5 Replies View Related

SQLDataSource1.Update();

Jan 19, 2008

I am using SQLDataSource1.Update() in my update button
but nothing is updating, why? how to make it work?

View 3 Replies View Related

Sqldatasource1.Select([Argument?])

Oct 8, 2007

Hi, nice to meet you all. I need to return a parameter value from a store procedure, i already done insert(), update(), delete() to return parameter back. Just only select() can't return parameter and it need argument, I try to write in Sqldatasource1.Select(Argument.empty), it can't work and return null. How should i solve the problem? Or I wirte the wrong argument? Can anyone help me? Thank in advance.

View 5 Replies View Related

Retuen 1 Fild On SqlDataSource1.SelectParameters

Feb 28, 2007

 
 
ALTER PROCEDURE dbo.Default_Edit1
(
@ID int,
@Family Nvarchar (100) OutPut
)
AS
/* SET NOCOUNT ON */
SELECT @Family=Family FROM Table1 where (ID=@ID)
 
 
RETURN
 
 
SqlDataSource1.SelectParameters.Add("ID", Me.GridView1.DataKeys(CInt(e.CommandArgument)).Item(0))
SqlDataSource1.DeleteCommandType = SqlDataSourceCommandType.StoredProcedure
SqlDataSource1.SelectCommand = "dbo.Default_Edit1"
SqlDataSource1.SelectParameters("Family").Direction = Data.ParameterDirection.Output
Label3.Text = SqlDataSource1.SelectParameters("Family").Direction.ToString()
 
it's have error 
I went to return 1 fild
 ??
 
 

View 2 Replies View Related

How To Do Multiple Inserts For One Row Of Data?

Aug 21, 2006

I need to insert multiple rows for input rows that meet certain conditions.

My input data is as follows.

ZIPCode, Plus 4, Range, City, State

What I need to happen is that if there is a value in the range column that is > 0 then I need to insert a row for every range item.

For instance say I have the following data.

54952, 1001, 10, Menasha, WI

What I need imported is :

54952, 1001, Menasha, WI
54952, 1002, Menasha, WI
54952, 1003, Menasha, WI
54952, 1004, Menasha, WI
54952, 1005, Menasha, WI
54952, 1006, Menasha, WI
54952, 1007, Menasha, WI
54952, 1008, Mensaha, WI
54952, 1009, Mensaha, WI
54952, 1010, Mensaha, WI
54952, 1011, Mensaha, WI

Any help in pointing me in the right direction would be great. Thanks for your help in advance.

View 2 Replies View Related

How To Access By Code Table Returned By SqlDataSource1 ???

Jun 5, 2008

Hi to all,
I'm writting code that needs to pass data returned by a SqlDataSource object to another object (user control to graph data)
Query in SqlDataSource object is OK, I've seen data returned by it at a GridView Object but I need to pass that data to an user control that needs a reference to the table that has the data
... What would be the code that do that task ??
 I'm new to develop web applications... using Visual Web Developer Express 2008
Help in advance

View 1 Replies View Related

Textbox Inserts Data Into Database

Apr 13, 2008

I have a VERY simple program, it contains a datagrid, textbox and button
 I want it so when I insert something into the textbox and press the button it puts it into the database that is connected to the datagrid and displays it
 I have the following code and I cannot get it to work:
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
 Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs)
SqlDataSource1.InsertParameters.Add("@Name", TextBox1.Text)
End Sub
 </script>
<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">
<title>Untitled Page</title></head>
<body><form id="Form1" action="Default.aspx" runat="server">
<table>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display.">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>"DeleteCommand="DELETE FROM [Table] WHERE [ID] = @ID"
InsertCommand="INSERT INTO [Table] ([Name]) VALUES (@Name)"
ProviderName="<%$ ConnectionStrings:DatabaseConnectionString1.ProviderName %>"SelectCommand="SELECT [ID], [Name] FROM [Table]"
UpdateCommand="UPDATE [Table] SET [Name] = @Name WHERE [ID] = @ID">
<InsertParameters>
<asp:Parameter Name="Name" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td align="center">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click1" />
</td></tr>
</table></form>
</body>
</html>

View 2 Replies View Related

Export Data From Table As SQL Inserts

Jul 21, 2005

Hi,

I have data in an old database I would like to capture for my new
system but I dont have the original insert scripts.  Is there a
tool (in SQL Server 2000 or thirdparty) that will help me export the
data as SQL inserts?

Thanks

jr.

View 1 Replies View Related

Any Way To Ignore Data On Inserts That Violate A Rule?

Apr 18, 2012

I am currently importing tick data for a stock. Let's say my table structure is like this:

CREATE TABLE tick
(
tickId bigint identity(1,1) primary key
, tickTime datetime
, price money
)

If the stream of data I get resembles:

'4/17/12 2:00:00.000', 10.00
'4/17/12 2:00:02.000', 10.02
'4/17/12 2:00:01.000', 10.01
'4/17/12 2:00:03.000', 10.03

I want my table to look like this:

1, '4/17/12 2:00:00.000', 10.00
2, '4/17/12 2:00:02.000', 10.02
3, '4/17/12 2:00:03.000', 10.03

Essentially ignoring the out of place '4/17/12 2:00:01.000' record. What is the least expensive way to accomplish this?

View 6 Replies View Related

Bulk Inserts To Data Warehouse - Best Practices?

Jul 20, 2005

Hello all,I just started a new job this week and they complain about the length oftime it takes to load data into their data warehouse,which they do once a month.From what I can gather, they rebuild the indexes before the insert with an80% Fillfactor, then insert the data (with theindexes enabled), then rebuild the indexes with a 100% Fillfactor.Most of my RDBMS experience is with a different product. We would havedisabled the indexes and Foreign Keys, loaded the data, thenre-enabled them, moving any records that violated the constraints into anappropriate audit table to be checked after.Can someone share with me what the accepted "best practices" are for loadingdata efficiently into a data warehouse?Any thoughts would be deeply appreciated.Steve

View 2 Replies View Related

Master Data Services :: Preventing Duplicate Inserts

Mar 4, 2015

In my trivial example below I have a Nationality entity. The entity just has the code and Name attributes, with the code being an automatically generated Integer. I am inserting one record and then trying to prevent the same record being inserted, by setting the ImportType to 1:

truncate table [stg].[Nationality_1_Leaf]
insert into [stg].[Nationality_1_Leaf](importType, ImportStatus_id, BatchTag, Name)
values(1, 0, 'some batch' , 'American' )
select * From [stg].[Nationality_1_Leaf]
exec stg.udp_Nationality_1_Leaf 'VERSION_1', 1, 'some batch'

After this I truncate the staging table and repeat the process. Unfortunately a new record is entered into the Entity even though the name is identical to a record that already exists.

View 13 Replies View Related

Which Method Is Better For Transfering Data Using Direct Inserts/SSIS?

Feb 7, 2007

Hi

I'm transfering legecy data to SQL Server.

Can anybody tell which method is best.

My boss wants cutome user interface to choose options and Need to update UI during processing.

Currently I'm using Direct INSERT Stmt (T-sql) Execution.

Can Anybody suggest the best.

View 1 Replies View Related

SQL Server 2008 :: Add A Trigger That Inserts Original Data From 1 Table To Another

Apr 10, 2015

I am trying to create a trigger on a table. Let's call it table ABC. Table looks like this:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ABC](
[id] [uniqueidentifier] NOT NULL,

[Code] ....

When someone updates a row on table ABC, I want to insert the original values along with the current date and time getdate() into table ABCD with the current date and time into the updateDate field as defined below:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ABCD](
[id] [uniqueidentifier] NOT NULL,

[Code] .....

The trigger I've currently written looks like this:

/****** Object: Trigger [dbo].[ABC_trigger] Script Date: 4/10/2015 1:32:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[ABC_trigger] ON [dbo].[ABC]

[Code] ...

This trigger works, but it inserts all of the rows every time. My question is how can I get the trigger to just insert the last row updated?

I can't sort by uniqueidentifier in descending as those can be random.

View 9 Replies View Related

Can A Script Handle Conditional Inserts To An OLDB Data Source?

Nov 20, 2007

I have a very simple SSIS task whcih opens a flat file data source, checks the first two characters of each row and if it is equal to "06", inserts that row into an OLDB destination table. However it is inserting EVERY row, even the ones not equal to "06" in first two columns. So, how do I get it to NOT insert the rows I don't want? Any help is very much appreciated and the following is my code:


Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

Dim InactiveDate As String

If Left(Row.Column0, 2) = "06" Then

Row.FilingNbr = Mid(Row.Column0, 3, 10)

Row.Address1 = Mid(Row.Column0, 13, 50)

Row.Address2 = Mid(Row.Column0, 63, 50)

Row.City = Mid(Row.Column0, 113, 64)

Row.State = Mid(Row.Column0, 177, 4)

Row.Zip = Mid(Row.Column0, 181, 9)

Row.ZipExt = Mid(Row.Column0, 190, 6)

Row.AgentCountry = Mid(Row.Column0, 196, 64)

InactiveDate = Mid(Row.Column0, 264, 2) + "/" + Mid(Row.Column0, 266, 2) + "/" + Mid(Row.Column0, 260, 4)

If IsDate(InactiveDate) And InactiveDate <> "00/00/0000" Then

Row.AgentInactiveDate = InactiveDate

Else

Row.AgentInactiveDate_IsNull = True

End If

Row.AgentLastName = Mid(Row.Column0, 268, 50)

Row.AgentFirstName = Mid(Row.Column0, 318, 50)

Row.AgentMiddleName = Mid(Row.Column0, 368, 50)

Row.AgentSuffix = Mid(Row.Column0, 418, 6)

End If



End Sub


Karen

View 5 Replies View Related

Does The Configure Data Source Wizard Work For Updates,Inserts, And Deletes ?

Jun 8, 2007

Ok, I think this may have a simple answer. Basically I have no problems in setting up QueryString/Control/etc parameters when I use SELECT in the Configure Data Source Wizard as it prompts me for the necessary parameters. But when I try to use the Configure Data Source Wizard with an UPDATE, INSERT or DELETE it does NOT prompt me for the required parameters.Is this a bug or am I just missing something? Do I have to put them in manually or something?Thanks! 

View 5 Replies View Related

Better Practices Wanted For Cascading Inserts Of Hierarchical Data From Staging Tables

Aug 28, 2007

I apologize if this has been asked, but I can't find a complete answer.

We have a situation with parent/child tables which have an identity column as their PK. We need to be able to insert into the live tables from staging tables. The data in the staging tables are related via a surrogate key.

I have found the OUTPUT clause, but that can only refer to columns of the actual table (since there is no FROM clause in an INSERT). Our current best solution to this problem involves adding bogus "staging" columns to the destination tables, and removing them after we've inserted everything from staging. This is an unattractive solution to say the least.

I'll give an example that mirrors our actual solution, and ask if anyone has a better solution?
----------




Code Snippet
CREATE TABLE [dbo].[TABLE_A](
[ID] [int] IDENTITY(1,1) NOT NULL,
[DATA] [nchar](10) NOT NULL,
[STAGING_COLUMN] [bigint] NULL,
CONSTRAINT [PK_TABLE_A] PRIMARY KEY ([ID] ASC)
)
GO
CREATE TABLE [dbo].[TABLE_B](
[ID] [int] IDENTITY(1,1) NOT NULL,
[A_ID] [int] NOT NULL,
[DATA] [nchar](10) NOT NULL,
[STAGING_COLUMN] [bigint] NULL,
CONSTRAINT [PK_TABLE_B] PRIMARY KEY ([ID] ASC)
)
GO
ALTER TABLE [dbo].[TABLE_B]
ADD CONSTRAINT [FK_TABLE_A_TABLE_B] FOREIGN KEY([A_ID]) REFERENCES [dbo].[TABLE_A] ([ID])
GO
CREATE TABLE [dbo].[STAGE_TABLE_A](
[A_Key] [bigint] NOT NULL,
[DATA] [nchar](10) NOT NULL
)
GO
CREATE TABLE [dbo].[STAGE_TABLE_B](
[B_Key] [bigint] NOT NULL,
[DATA] [nchar](10) NOT NULL,
[A_Key] [bigint] NOT NULL
)
GO


The STAGING_COLUMN columns are the ones that will be added before, and dropped after.






Code Snippet
DECLARE @TABLE_A_MAP TABLE (
A_ID INT,
A_Key BIGINT
)
INSERT INTO TABLE_A (DATA, STAGING_COLUMN)
OUTPUT INSERTED.ID, INSERTED.STAGING_COLUMN INTO @TABLE_A_MAP
SELECT DATA, A_Key FROM STAGE_TABLE_A
INSERT INTO TABLE_B (A_ID, DATA)
SELECT TAM.A_ID, STB.DATA
FROM STAGE_TABLE_B STB INNER JOIN @TABLE_A_MAP TAM ON TAM.A_Key = STB.A_Key






This seems to work, but I'd really like another alternative. Even though this is happening when nobody else is using the database, I cringe at the thought of adding and removing columns just to make this work.

Here are a few of my constraints:



The above is a simplification of the actual problem. The actual problem goes about five levels deep (hence the B_Key in STAGE_TABLE_B). At the top level, our larger customer will have 100,000 rows to insert. Each level will average 3 times as many rows as the next higher level, so we're talking about real volumes here.

This has to finish over the course of a weekend.

This has to be delivered to QA this Friday
Thanks for any help or insight.

View 3 Replies View Related

SQL Server 2014 :: Stored Procedure That Inserts And Updates A Table With Excel Data?

May 27, 2014

I need a script that inserts the data of an excel sheet into a table. If something already exists it should leave it, unless it's edited in the excel sheet and so on and so on. This proces has to go through a stored procedure... ...But how?

View 6 Replies View Related

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

Feb 26, 2015

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

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

Below is the code i have at the moment

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

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

[Code] .....

View 1 Replies View Related

How Can I Do A Multiple Insert Or Multiple Updates Or Inserts And Updates To The Same Table..

Oct 30, 2007

Hi...
 I have data that i am getting through a dbf file. and i am dumping that data to a sql server... and then taking the data from the sql server after scrubing it i put it into the production database.. right my stored procedure handles a single plan only... but now there may be two or more plans together in the same sql server database which i need to scrub and then update that particular plan already exists or inserts if they dont...
 
this is my sproc...
 ALTER PROCEDURE [dbo].[usp_Import_Plan]
@ClientId int,
@UserId int = NULL,
@HistoryId int,
@ShowStatus bit = 0-- Indicates whether status messages should be returned during the import.

AS

SET NOCOUNT ON

DECLARE
@Count int,
@Sproc varchar(50),
@Status varchar(200),
@TotalCount int

SET @Sproc = OBJECT_NAME(@@ProcId)

SET @Status = 'Updating plan information in Plan table.'
UPDATE
Statements..Plan
SET
PlanName = PlanName1,
Description = PlanName2
FROM
Statements..Plan cp
JOIN (
SELECT DISTINCT
PlanId,
PlanName1,
PlanName2
FROM
Census
) c
ON cp.CPlanId = c.PlanId
WHERE
cp.ClientId = @ClientId
AND
(
IsNull(cp.PlanName,'') <> IsNull(c.PlanName1,'')
OR
IsNull(cp.Description,'') <> IsNull(c.PlanName2,'')
)

SET @Count = @@ROWCOUNT
IF @Count > 0
BEGIN
SET @Status = 'Updated ' + Cast(@Count AS varchar(10)) + ' record(s) in ClientPlan.'
END
ELSE
BEGIN
SET @Status = 'No records were updated in Plan.'
END

SET @Status = 'Adding plan information to Plan table.'
INSERT INTO Statements..Plan (
ClientId,
ClientPlanId,
UserId,
PlanName,
Description
)
SELECT DISTINCT
@ClientId,
CPlanId,
@UserId,
PlanName1,
PlanName2
FROM
Census
WHERE
PlanId NOT IN (
SELECT DISTINCT
CPlanId
FROM
Statements..Plan
WHERE
ClientId = @ClientId
AND
ClientPlanId IS NOT NULL
)

SET @Count = @@ROWCOUNT
IF @Count > 0
BEGIN
SET @Status = 'Added ' + Cast(@Count AS varchar(10)) + ' record(s) to Plan.'
END
ELSE
BEGIN
SET @Status = 'No information was added Plan.'
END

SET NOCOUNT OFF
 
So how do i do multiple inserts and updates using this stored procedure...
 
Regards
Karen

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

Can't Insert New Data To Sql Using Sqldatasource.insert, Web Forms And A Master Page

Sep 11, 2006

Hello, I'm new to the forum and new to SQL, ASP.NET, etc.  I am creating an intranet site for my company in VS 2005 and have run into a very annoying problem that I can't seem to solve.  I have tried Googling it and came up empty.  I have a database in SQL Express 2005 and my website will be accessing several tables within the database.  I can retrieve info just fine and I can update, delete, etc just fine using gridview or other prebuilt tools, but when I add a few text boxes and wire a button to the SqlDataSource.Insert() command, I get a new record that is full of null values except for the identity key I have set.  The kicker is that I am also using a master page and when I duplicate the web page without the master page link, everything works just fine.  The following snippets show what I'm doing:<InsertParameters><asp:FormParameter Name="Name" Type="String" FormField="txtName" /><asp:FormParameter Name="Location" Type="String" FormField="ddlLocation" /><asp:FormParameter Name="Issue" Type="String" FormField="txtProblem" /></InsertParameters>Of course I match the formfields to the text boxes, create an onclick event for my button, the sqldatasource is configured correctly, it just doesn't work with the master page no matter what I do. Any help would be appreciated. Thanks

View 3 Replies View Related

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

Apr 20, 2008

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

View 1 Replies View Related

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

Oct 12, 2007



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

3
123||
456||
789||

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


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

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

can anyone help me how to do this?

Thanks,
-Badri

View 5 Replies View Related

How Do I Call A Stored Procedure To Insert Data In SQL Server In SSIS Data Flow Task

Jan 29, 2008



I need to call a stored procedure to insert data into a table in SQL Server from SSIS data flow task.
I am currently trying to use OLe Db Destination, but I am not sure how to map inputs to OLE DB Destination to my stored procedure insert.
Thanks

View 6 Replies View Related

SQL Server 2014 :: How To Insert CSV Data Into DB Where Some Data Don't Have Double Quotes

Aug 11, 2015

Example of data in CSV are as follows:

"XXX","0001",-990039739 ,0 ,0 ,0 ,0 ,0 ,0
"ABC"," ",-3422054702 ,0 ,481385 ,0 ,0 ,0 ,0
"JJZ","0001",0 ,0 ,0 ,0 ,0 ,0 ,0Here's my format:
12.0
10
1 SQLCHAR 0 0 """ 0 "" ""
2 SQLCHAR 0 5 "","" 1 OKCCY SQL_Latin1_General_CP1_CI_AS

[Code] ....

View 5 Replies View Related

Insert Data To A Table Where Select Data From Another SERVER

Oct 8, 2007

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

View 1 Replies View Related

Inserts Per Second

Mar 3, 2006

Just curios,

I have four 72 GB Drive on a RAID 5

Disk Specs
IO/Second = 130 per disk
Speed RPM = 15 K

When I did a load test of inserting data into a table
with four Columns

Col1 INT
Col2 VARCHAR(32)
Col3 VARCHAR(4000)
Col4 DATETIME

I could insert around 1044 Inserts per second where as
I thought I could do max of 520 Inserts ( 130 * 4 ) because
each disk can only take 130 Inserts multiplied by 4 Disks
gives me a theoritical limit of 520.

Also How does the Query Analyser Connects to the datbase
Server.. does it use ODBC

Thx
Venu

View 1 Replies View Related







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