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


ADVERTISEMENT

Duplicate Records Are Being Inserted With One Insert Command.

Jul 20, 2005

This is like the bug from hell. It is kind of hard to explain, soplease bear with me.Background Info: SQL Server 7.0, on an NT box, Active Server pageswith Javascript, using ADO objects.I'm inserting simple records into a table. But one insert command isplacing 2 or 3 records into the table. The 'extra' records, have thesame data as the previous insert incident, (except for the timestamp).Here is an example. Follow the values of the 'Search String' field:I inserted one record at a time, in the following order (And only oneinsert per item):airplanejetdogcatmousetigerAfter this, I should have had 6 records in the table. But, I endedup with 11!Here is what was recorded in the database:Vid DateTime Type ProductName SearchString NumResultscgcgGeorgeWeb3 Fri Sep 26 09:48:26 PDT 2003 i null airplane 112cgcgGeorgeWeb3 Fri Sep 26 09:49:37 PDT 2003 i null jet 52cgcgGeorgeWeb3 Fri Sep 26 09:50:00 PDT 2003 i null dog 49cgcgGeorgeWeb3 Fri Sep 26 09:50:00 PDT 2003 i null jet 52cgcgGeorgeWeb3 Fri Sep 26 09:50:00 PDT 2003 i null jet 52cgcgGeorgeWeb3 Fri Sep 26 09:50:22 PDT 2003 i null dog 49cgcgGeorgeWeb3 Fri Sep 26 09:50:22 PDT 2003 i null cat 75cgcgGeorgeWeb3 Fri Sep 26 09:52:53 PDT 2003 i null mouse 64cgcgGeorgeWeb3 Fri Sep 26 09:53:06 PDT 2003 i null tiger 14cgcgGeorgeWeb3 Fri Sep 26 09:53:06 PDT 2003 i null mouse 64cgcgGeorgeWeb3 Fri Sep 26 09:53:06 PDT 2003 i null mouse 64Look at the timestamps, and notice which ones are the same.I did one insert for 'dog' , but notice how 2 'jet' records wereinsertedat the same time. Then, when I inserted the 'cat' record, another'dog' record was inserted. I waited awhile, and inserted mouse, andonly the mouse was inserted. But soon after, I inserted 'tiger', and 2more mouse records were inserted.If I wait awhile between inserts, then no extra records are inserted.( Notice 'airplane', and the first 'mouse' entries. ) But if I insertrecords right after one another, then the second record insertion alsoinserts a record with data from the 1st insertion.Here is the complete function, in Javascript (The main code ofinterestmay start at the Query = "INSERT ... statement):----------------------------------------------------------------------//Write SearchTrack Record ------------------------------------Search.prototype.writeSearchTrackRec = function(){Response.Write ("<br>Calling function writeSearchTrack "); // fordebugvar Query;var vid;var type = "i"; // Type is imagevar Q = "', '";var datetime = "GETDATE()";//Get the Vid// First - try to get from the outVid var of Cookieinctry{vid = outVid;}catch(e){vid = Request.Cookies("CGIVid"); // Gets cookie id valuevid = ""+vid;if (vid == 'undefined' || vid == ""){vid = "ImageSearchNoVid";}}try{Query = "INSERT SearchTrack (Vid, Type, SearchString, DateTime,NumResults) ";Query += "VALUES ('"+vid+Q+type+Q+this.searchString+"',"+datetime+","+this.numResults+ ")";this.cmd.CommandText = Query;this.cmd.Execute();}catch(e){writeGenericErrLog("Insert SearchTrack failed", "Vid: "+vid+"- SearchString:: "+this.searchString+" - NumResults: "+this.numResults, e.description);}}//end-----------------------------------------------------------------I also wrote a non-object oriented function, and created the commandobject inside the function. But I had the same results.I know that the function is not getting called multiple timesbecause I print out a message each time it is called.This really stumps me. I'll really appreciate any help you canoffer.Thanks,George

View 2 Replies View Related

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

Feb 26, 2015

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

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

Below is the code i have at the moment

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

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

[Code] .....

View 1 Replies View Related

Data Access :: Bulk Fetch Records And Insert / Update Same In Other Table With Some Business Logic

Apr 21, 2015

I am currently working with C and SQL Server 2012. My requirement is to Bulk fetch the records and Insert/Update the same in the other table with some  business logic? How do i do this?

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

Insert / Update In Master Table And Also Save A History Of Changed Records : Using Data Flow/simple Sql Queries

Feb 9, 2007

Hi,

My scenario:

I have a master securities table which has 7 fields. As a part of the daily process I am uploading flat files into database tables. The flat files contains the master(static) security data as well as the analytics(transaction) data. I need to

1) separate the master (static) data from the flat files,

2) check whether that data is present in the master table, if not then insert that data into the master table

3) If data present then move that existing record to an history table and then update the main master table.

All the 7 fields need to be checked to uniquely identify a single record in the master table.

How can this be done? Whether we can us a combination of data flow items or write a sql procedure to do all this.

Thanks in advance for your help.

Regards,

$wapnil

View 4 Replies View Related

SQL INSERT Command From One Table To Another?

Dec 19, 2007

i have a question if anyone can help please..
i have need to create a database table as a go-between, where users will upload info.  then on a backend page admin will make some data settings, then transfer it to the proper, permanent tables.(all this to avoid expecting users themselves to upload files to proper places).
can i use a basic SQL INSERT statement to move from one table directly to another without the use of parameters? for example,
INSERT INTO tblOne (fieldOne,fieldTwo,fieldThree) VALUES (tblTwo(fieldOne,fieldTwo,fieldThree)
if so, what is the syntax? and if not, then what would i have to do, just use some go between variables or objects? perhaps a DataSet to pull the values, then use same DataSet to load the values into new table, then a simple DELETE statement on the intermediate table?
i mean, i can work my way through this, but if anybody has gone through a similar situation i sure could use any pointers or tips to keep it as clean and simple as possible.
thanks all!

View 3 Replies View Related

Data Flow Task To Delete Records And Then Insert Records In Transaction

Aug 6, 2007

HI,

I have been trying to solve the locking problem from past couple of days. Please help mee!!

Scenario:
--------------
I have a SSIS package in which 2 data flow tasks. 1st data flow task deletes records from a 5 tables and the 2nd data flow task should insert records into 1 of the five tables after the success of 1st data flow task. This scenario runs in Transacation.

The above scenrio in the 2nd data flow task hangs in runtime. It does not complete. with sp_who2 command i could see that there is an intent share lock(LK_M_IS) on the table and the status is SUSPENDED.

I dont know how to come out of this locking. Please help.

Thanks ,
Sunil

View 7 Replies View Related

Insert Fails When Table Schema Changes

Nov 22, 2006

 

I always got this error when i change the identity key of the table A to yes or no

when i performing an insert into table B and b,accountid is in table A .

seems that when i save, the foreign keys reflect a change of schema...and when i do an insert operation, it fails.

how can i avoid such thinsg to happen?  i m using a cursor to load the data and comparing them to see if they are already loaded in the table before inserting them,

ERROR -------------------------------------------------------------------------------------------------------------------------------------------------------------

Msg 16943, Level 16, State 4, Procedure LOADDEPOSIT, Line 167

Could not complete cursor operation because the table schema changed after the cursor was declared.

View 3 Replies View Related

Data Lost After INSERT Command

Dec 21, 2006

I have a website that is used to enter dates from a calendar. For example, user A might go to the website and select 20 different days in January. When user A clicks on the Save button the dates are written to the database with an INSERT command. This works fine. However, when user B then goes through the same procedure, say selecting 5 dates that are in the set selected by user A, those dates are properly saved in the database but the rows containing user A's same 5 dates disappear. I suspect this is something simple but I'm new and ignorant. Please help.

View 4 Replies View Related

Insert Using Subquery Fails To Insert With No Error

Apr 10, 2008

I am working with parent child tables and want to populate the primary key on insert so that the user does not have to enter this for each record.  Here is my codeInsertCommand="INSERT INTO [Awards] ([UFID], [DateAwarded], [Amount], [AwardingAgency]) Select UFID, @DateAwarded, @Amount, @AwardingAgency from master where GatorlinkName = @LoginName"  <InsertParameters><asp:Parameter Name="LoginName" Type="String" />         <asp:Parameter Name="strusername" Type="String" />            <asp:Parameter Name="UFID" Type="String" />            <asp:Parameter Name="DateAwarded" Type="DateTime" />            <asp:Parameter Name="Amount" Type="Decimal" />            <asp:Parameter Name="AwardingAgency" Type="String" />        </InsertParameters> The UFID field is the only field that should be populated from SQL data the others are coming from a form view insert form.  When I run an insert I get no error but the insert does not happen. I know that the @LoginName works since I am using this same logic in my select statement.  Thanks in advance for your help,Ken 

View 3 Replies View Related

INSERT Command - Retrieve PK While Inserting To Table

Sep 16, 2009

I have a primary key named pk, name and surname fields. I need to insert to my table names and surnames.

INSERT INTO People (name,surname) VALUES ('john','black');

I'm not giving pks database gives is auto. But my problem is i need to know the pk that my database gave. Because i have lots of duplicate records. Is there any way to retrieve pk while inserting to table.

View 7 Replies View Related

Binary Data Insert Fails Using Dblib

Jul 30, 2004

who still uses the old dblib can help me?
thanks in advance:


1.create table & procedure in db:
test_table(uniqueidentifier a,varbinary50 b)
CREATE PROCEDURE insert_table
@b_in varbinary
AS
insert into test_table(b) values (@b_in)
GO

2.write program use dblib:
wchar_t str[120]=L"ABC";
dbrpcparam(dbproc[i], "@b_in", (BYTE)NULL, SQLVARBINARY,
-1, 6, &str)

3.I can find the program executed successfully,but only 1 Byte is inserted:
a b
-----------------------------------------------
199D71BE-327A-4BC1-AEC8-ACB0C96076CA 0x41



how to insert the whole string into the database?

View 2 Replies View Related

How To Write Command For Insert Data With Running Number

Jan 11, 2008

My table has a running number primary key. I want to insert data to this table and automatically generate running number pk. I try to write SQL command like this.
SELECT MAX(ID) AS MaxId from test
INSERT INTO test (ID, data1, data2, data3) VALUES (MaxId+1, @data1, @data2, @data3)
but it fails. How should I do? Thank you in advance

View 1 Replies View Related

Insert Varbinary Data Using Command-line Sqlcmd

May 23, 2008



Hi,

I have a SQL script file which creates a table and and inserts all data required by the client app into the table.

The table also holds images in a varbinary field. How do I insert an image held on the file system (e.g. "C:ImagesMyImage.gif") into a varbinary field using a script that is run using sqlcmd on the command line?


Any pointers greatly appreciated!

Mike

View 8 Replies View Related

Bulk Insert Fails. Column Is Too Long In The Data File

Jun 27, 2006

Hi,

for testing purposes I'm inserting a flat file into a sql-server table using BULK INSERT unsig the following code:

BULK INSERT rsk_staging
FROM 'c: empulk
sk.txt'
  WITH (
    FIELDTERMINATOR = '',
    ROWTERMINATOR = '
',
    CODEPAGE = 'RAW',
    DATAFILETYPE  = 'char',
    BATCHSIZE = 100000,
    ROWS_PER_BATCH = 1925604,
    TABLOCK
  )

I have two versions of "rsk.txt" one with 1.9mill rows and one with the first 2000 rows only. The files have one column only with 115 characters that I'll split in to several columns later using SUBSTRING. The one with 2000 rows fires in to the database with no problems whatsoever using this exact code, the other one throws the following error:

Server: Msg 4866, Level 17, State 66, Line 1
Bulk Insert fails. Column is too long in the data file for row 1, column 1. Make sure the field terminator and row terminator are specified correctly.

How can I resolve this problem?

EDIT: I tried several different row- and fieldterminators but this exact one works for the small data-file so I assume it should also work for the large one...the large one is however copyed directly using binary ftp from a unix-filesystem and the small one is manually copied into a new txt-file using UltraEdit.

View 1 Replies View Related

Insert Records From Same Table

Jul 14, 2014

I have a table that holds Customer Part numbers.

Cus_no item_no
100 ABC
100 XYZ
200 ABC
300 XYZ

Looking at the data above. I want look at customer 100 and insert all of customer 100's records where other customers do not match.

Table name ItemCust

After running my script I would expect my data to look like:

Cus_no item_no
100 ABC
100 XYZ
200 ABC
200 XYZ
300 ABC
300 XYZ

View 3 Replies View Related

Bulk Insert Fails To Import Data Files Created On Unix

Sep 21, 2006

It seems to me that files created on Unix machines with line terminator , or chr(10), cannot be imported using the Bulk Insert statement. Is this a bug, or an oversight by Microsoft? Does this mean that unless one replaces all with
, there is no way to use Bulk Insert to import Unix files? This is a very strange behavior by MSSQL. Even lessor programs such as Excel and Word automatically recognize chr(10) as a line termination character. Am I missing something, or is this just the way MSSQL is?

View 7 Replies View Related

How To Insert Multiple Records Into Table

Oct 11, 2007

insert into table1 (colname) values (value1)
can only insert one record into the table. How to insert multiple records as value1, value2, value3... into a table?
 We can of course use the above repeatedly, but if I don't know how many records (which is a variable), and I want to write a code which just take
value1, value2, value3 ....
from the clipboard, to paste as a input. How to insert those multiple records into table without split it. Thanks

View 5 Replies View Related

Updated Records From A Table Insert Into Another

Jul 26, 2007

Hi:

I need to create a trigger to save every record which has been updated in a table (e.g. "Contacts") into another (e.g. "Shadow_contacts). So basically something like a versioning on database level.
I have no experience with it and any precise hints/solutions would be very appreciated

selmahan

View 1 Replies View Related

Trigger To Insert Records In The Same Table?

Dec 23, 2011

we have various user defined fields, so when the user insert new value to this field , i want new records (other user field to get populated) be inserted relevant to the inserted value FROM another table (lookup)

This field is a drop down list , after insert committed , i want other user defined field to populate.

Scenario. Drop down is a list of users, after selecting and updating then i want contact details of the above selected user be populated.

CREATE TRIGGER User_Defined_field_KAE
ON [dbo].[AMGR_User_Fields_Tbl]
AFTER
INSERT

AS

INSERT INTO [dbo].[AMGR_User_Fields_Tbl]
(Client_Id,
Type_Id,
name
SELECT
Client_Id,
'1089',
A.USER_PHONE_1
FROM inserted , [dbo].[ADMN_User_Details] as A
WHERE name = a.user_id;

View 11 Replies View Related

Insert Records When Not In Target Table

Dec 29, 2014

I have need to insert records when not in the target table.

sample ddl for source and target tables. Notice the target table is missing the 'Upstairs' Rows:

CREATE TABLE source (
property_id INT,
unit_type VARCHAR(30),
care_type_id VARCHAR(1),
propert_room_type_id INT,
rate MONEY)

[code]....

View 2 Replies View Related

Insert Or Update Data Records

Mar 30, 2006

I'd like to do the following thing with a data flow task

Get all the records from a source (for example customers from a textfile, flat file source)
Then check for each record if the customer already exists in a table, for example with a customerID. If not, insert the record in the table (ole db destination), else copy the customer thats already in the table to another table (history table) and update the record with the customer from the textfile.

Is this possible?, and what kind of data flow transformation do I need?

View 1 Replies View Related

Insert Records Into A Table With Foreign Keys

May 21, 2008

i'm using sql express, management studio express and a visual web developer starter kit.
i have 4 tables: items; categories; categorization; old_items
the old_items table has both the item id and category fields in it, the new db has them separated: items.id; categories.id; categorization.itemId, categorizaton.parentCategoryId, both of which are foreign keys.
i need to get the old_item.id and old_item.category values into the new categorization table but it keeps choking on the foreign keys and i can't get past it.  as far as i've been able to figure out so far, i need to turn off the foreign keys to do the insert but i'm not sure and i haven't been able to find any sql query examples that demonstrate it or explain it well enough for my n00b self.
i've read http://msdn.microsoft.com/en-us/library/10cetyt6.aspx, "How to: Disable Foreign Key Constraints with INSERT and UPDATE Statements" but i don't get how that affects it, it seems like one of the other options would actually disable them.
can anyone help?  i've been trying all the permutations of queries i can think of and not getting it.
thanks.

View 5 Replies View Related

How To Insert Multiple Records Into Sql 2000 Table At Once ?

Nov 25, 2004

hello,
I am new to Slq 2000 Database,Now I create an asp.net application with sql 2000,
in my database I have two 2 table lets' say "OrderHead" and "OrderDetail",they look like this:
OrderHead orderdetail
---order no ----orderno
---issuedate ----itemname
---supplier ----desccription
---amount -----price
----Qty
Now I created a user-defined Collection class to storage order detail data in memory
and bind to a datagrid control.
I can transfer Collection data to xml file ,my problem as below :
There have multiple records data in my xml file,and I want to send the xml file as argument to a store procedure in sql 2000

anyone can give me some advise or some sample code ?

thanks in advanced!

View 2 Replies View Related

SQL 2012 :: How Many Records Can Insert Into A Temp Table

Mar 25, 2014

I use code below to insert data into a temp table.

How many records can insert into a temp table?

Select * into #temp from ORDER

View 3 Replies View Related

Bcp To Insert The Records From .dbf File Into A Sql Database Table

Apr 12, 2006

Hi

i need to inser the .dbf file records into sql table.

How should i go about it?

regards,

Kiran

View 6 Replies View Related

Transact SQL :: Insert Records To A Table From Different Tables

Aug 30, 2015

Lets say we are executing this query below to retrieve each customer and the amount associated to a table 

"INSERT INTO tblReceiptDue (Dealer, Amount) SELECT CustomerName, SUM(CASE WHEN VoucherType = 'Sales' then Outbound ELSE  - Inbound END) AS AMOUNT from
tblSaleStatementCustomer  WHERE CustomerType = 'Dealer' GROUP BY CustomerName"

Which display the data like below

DEALER                AMOUNT
------------------------------------------------
ABC                          2000
XYZ                          1000    

However I have one more table TABLE2 which contains two columns

DEALER                OPENING
-------------------------------------------------------
ABC                               5000
XYZ                               7000

I want to modify my query in such a way that AMOUNT column should also add

OPENING from TABLE2 So that I must get the result like below

DEALER                AMOUNT
------------------------------------------------
ABC                            7000
XYZ                             8000    

View 10 Replies View Related

Can I Insert Records Into A Table From A Stored Procedure

Oct 9, 2007

I have a long complicated storeed procedure that ends by returning the results of a select statement or dataset.

I use the logic in other sprocs too.

Can I Isert the returned dataset into a table variable or user table. sp_AddNamesList returns a list of names. For example something like....

INSERT INTO Insurance (Name)
Exec sp_AddNamesList

Thanks,

Mike

View 5 Replies View Related

Insert Multiple Records Into A Single Field On Another Table

Feb 15, 2012

I have a table JOBCODE which contains a list of codes.

I want to insert these values into table VIEWS as a list separated by spaces.

E.G.

Table Jobcodes looks like this

code
1
2
3
4
5
6

And I want table Views to look like this:

field1
1 2 3 4 5 6

How do I go about this?

View 4 Replies View Related

Query To Insert Records Into A Table Based On Request

Jul 31, 2014

I have a query to insert records into a table based on a request but the query can only read one record at a time. How do i change the query such that it is able to read multiple records. In the below query i was able to input only 1 request which is 149906.

Query

declare @num_of_times int
declare @Count INT
DECLARE @newrequestid varchar(50)
DECLARE @Frequency VARCHAR(25), @RequestId INT, @x INT, @Max INT, @RptDesc INT
SET @RequestId = 149906
SET @x = 1

[Code] ....

View 1 Replies View Related

Defining Command,commandtype And Connectionstring For SELECT Command Is Not Similar To INSERT And UPDATE

Feb 23, 2007

i am using visual web developer 2005 and SQL 2005 with VB as the code behindi am using INSERT command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString1").ToString()        test.InsertCommandType = SqlDataSourceCommandType.Text        test.InsertCommand = "INSERT INTO try (roll,name, age, email) VALUES (@roll,@name, @age, @email) "                  test.InsertParameters.Add("roll", TextBox1.Text)        test.InsertParameters.Add("name", TextBox2.Text)        test.InsertParameters.Add("age", TextBox3.Text)        test.InsertParameters.Add("email", TextBox4.Text)        test.Insert() i am using UPDATE command like this        Dim test As New SqlDataSource()        test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString()        test.UpdateCommandType = SqlDataSourceCommandType.Text        test.UpdateCommand = "UPDATE try SET name = '" + myname + "' , age = '" + myage + "' , email = '" + myemail + "' WHERE roll                                                         123 "        test.Update()but i have to use the SELECT command like this which is completely different from INSERT and  UPDATE commands   Dim tblData As New Data.DataTable()         Dim conn As New Data.SqlClient.SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated                                                                                Security=True;User Instance=True")   Dim Command As New Data.SqlClient.SqlCommand("SELECT * FROM try WHERE age = '100' ", conn)   Dim da As New Data.SqlClient.SqlDataAdapter(Command)   da.Fill(tblData)   conn.Close()                   TextBox4.Text = tblData.Rows(1).Item("name").ToString()        TextBox5.Text = tblData.Rows(1).Item("age").ToString()        TextBox6.Text = tblData.Rows(1).Item("email").ToString()       for INSERT and UPDATE commands defining the command,commandtype and connectionstring is samebut for the SELECT command it is completely different. why ?can i define the command,commandtype and connectionstring for SELECT command similar to INSERT and UPDATE ?if its possible how to do ?please help me

View 2 Replies View Related

SQL Server 2014 :: Add Multiple Records To Table (insert / Select)?

Jul 31, 2014

I am trying to add multiple records to my table (insert/select).

INSERT INTO Users
( User_id ,
Name
)
SELECT ( SELECT MAX(User_id) + 1
FROM Users
) ,
Name

But I get the error:

Violation of PRIMARY KEY constraint 'PK_Users'. Cannot insert duplicate key in object 'dbo.Users'.

But I am using the max User_id + 1, so it can't be duplicate

This would insert about 20 records.

Why the error?

View 7 Replies View Related







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