Dates When Inserting A Record

Nov 1, 2004

Is it possible to have sql server automatically record date and time (in a designated field)when a record is created in the db? This may seam basic but it has caused me a lot of grief.

View 8 Replies


ADVERTISEMENT

Restrict Inserting Record If Record Already Exist In Table

Apr 17, 2014

Is that possible to restrict inserting the record if record already exist in the table.

Scenario: query should be

We are inserting a bulk information of data, it should not insert the row if it already exist in the table. excluding that it should insert the other rows.

View 2 Replies View Related

Inserting Job Values Within Specified Dates

Sep 20, 2006

Hi all,I have a table called Jobs, with fields PK auto increment job_id, job_name, date. I'm using the visual web developer, .net 2.0, sql server 2005.I'm trying to have an option in one of my forms that allows me to add Jobs for a specific time frame. Say I want to add a job called "JobOne" and that I expect this job to last 2 months, so I would like to add this  "JobOne" from October 1st 2006 to December 1st 2006. Than in the table "jobs" I would see JobOne in October 1st, 2nd, 3rd... all the way to December 1st. I'm familiar how to insert single values from formviews, using sqldatasources but I have no idea how to insert something like this, so I was wondering if anyone out there could help.Thanks! 

View 1 Replies View Related

Please Help With Inserting Dates My Database

Dec 7, 2004

here is what happens..... i create a sql statement with a date parameter and execute the insert via my asp.net page.

strsql = "insert into table(id, lastdate, id2) values ('id'," & date.today & ",'id2')"


this produces the following date in my database which is 'smalldate' datatype = 1/1/1900

View 3 Replies View Related

Errors Inserting Dates

Oct 26, 2006

When i try to insert into a datetime field i keep getting this error.

Msg 242, Level 16, State 3, Procedure Sproc_01220_Tour_PendingPayment, Line 27
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.

(1 row(s) affected)

i am passing to the date parameters the date in this format dd/mm/yyyy

Any ideas


ALTER PROCEDURE [dbo].[Sproc_01220_Tour_PendingPayment]

@MemberIdint=Null,
@TourStartDateDateTime=Null,
@Initial_TourQtyint=Null,
@PaidUntillDateTime=Null


AS
BEGIN--Overall
SET NOCOUNT ON;

BEGIN--Insert

INSERT INTOTbl_01040_Tour_Join_PendingPayment
(Pend_MemberId,
Pend_TourStartDate,
Pend_Initial_TourQty,
Pend_PaidUntill)

VALUES (@MemberId,
@TourStartDate,
@Initial_TourQty,
@PaidUntill)

END--Insert

View 7 Replies View Related

Inserting Dates From Asp.net Application To SQL Server Db, Help.

Apr 18, 2008

 Hi Guys,I need some help here. I've created a asp.net reception system for internal use. The problem I'm having is this, when I update a record all the dates are saved as 01/01/1900. I've had a look at a couple of threads on various forums and sites but none of them seem to have a solution for my problem... I have an AJAX calenderExtenders on the date text boxes and i have played around with all different date formats, currently on yyyy/MM/dd. I've also tried DateTime.Parse(txtStartDate.text) but doesn't work. I pass all the parameters to a stored procedure on the sql server in the correct order. I've included my code below, I have only included date parameters. SqlConnection conn = null;        try        {            string connString =                ConfigurationManager.ConnectionStrings["RCM"].ConnectionString;            //Initialise the sqlConnection object            conn = new SqlConnection();            conn.ConnectionString = connString; //Getting connection string to the db            //Create the command            SqlCommand command = new SqlCommand("UpdateClient", conn);            command.CommandType = CommandType.StoredProcedure;            //Opening connection to the db            conn.Open();            //Setting input parameters                                           command.Parameters.AddWithValue("@DOB", txtDOB.Text);            command.Parameters.AddWithValue("@StartDate",txtStartDate.Text);                        //Execute T-SQL            command.ExecuteNonQuery();            //Close connection            command.Connection.Close();            conn.Close();        }        catch (Exception ex)        {            lblError.Text = "An error has occured: " + ex.Message;        } 

View 18 Replies View Related

Problem With Inserting Or Updating Dates In Mssql 2000

Apr 12, 2006

Hello.I've read many topics about this problem but i couldn't figure it out.I use form where user must insert 2 dates  using texboxes.-One is required and other is optional.Sql 2000 is inserting either '20061105' or '2006.11.05' on insert update but select query returns 05.11.2006 on my report. Question 1.How do I insert or update dates from my form where date is entered dd.mm.yyyy to sql 2000 table?question 2. What to do if user left optional texbox date empty.I'm using SP and function with arguments (byval texbox1.text as date, byval texbox2.text as date)and parameters @date1, sqldbtype date =texbox1.text

View 2 Replies View Related

Why Date Columns Default To 1900 After Inserting Dates In SQL Server Everywhere.?

Sep 19, 2006

I have created a sample Database for the school project,

After executing the query below, the Date column is supposed to have the dates I have entered before,

However the dates shown are 1900.

Any idea why is this happening?

I appreciate your help.

Thank you.
Query:
 
Drop table AccountReceivable
GO
--BEGIN TRANSACTION
Create table AccountReceivable
(
 AccountRecID int identity (1,1) not null,
 PatientID int not null,
 PresentCharges int default 0 not null,
 PaymentMade money default 0 not null,
 PreviousBalance money default 0 not null,
 BalanceDue money default 0 not null,
 LastPaymentDate datetime not null,
 PresentDate datetime default GetDate() not null
)
GO
ALTER TABLE AccountReceivable ADD CONSTRAINT
PK_AccountRecID Primary Key (AccountRecID)
GO
 
ALTER TABLE AccountReceivable ADD CONSTRAINT
FK_PatientID_PatientID FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID)
GO
--COMMIT
--query to find delinquent accounts
--DATEDIFF (d, LastPaymentDate, PresentDate)
 
--Populate the Accounts Table
DELETE AccountReceivable
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate )
                    VALUES (913235,451.34,50,0,401.34,4/7/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (918035,109,109,0,0,3/6/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                            VALUES (914235,279,89,0,190,5/9/2005,5/9/2005)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                            VALUES (914235,0,90,190,100,5/9/2005,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (912224,67.90,67.90,0,0,2/2/2006,DEFAULT)
GO
 
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (900814,678.32,78.32,0,600,4/6/2006,4/6/2006)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (900814,0,500,600,100,4/6/2006,4/16/2006)
 
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (900814,0,100,100,0,4/16/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (913010,203,0,100,303,2/6/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (913010,0,80,303,223,8/3/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (913230,1030.89,1030.89,0,0,4/16/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (918035,78,60,0,18,7/1/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (941235,902,502,0,400,8/15/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (941235,0,200,400,200,8/15/2006,DEFAULT)
 
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (952235,134,24,0,110,4/18/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (952235,0,20,110,90,4/18/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (921635,257.87,57.87,0,200,5/27/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (921635,0,20,200,180,6/27/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (915235,1204,200,0,1004,3/15/2006,DEFAULT)
 
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (915235,0,100,1004,904,4/27/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (900035,578,178,0,400,7/10/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (900035,0,100,400,300,7/19/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (913241,157,0,0,157,5/12/2006,DEFAULT)
GO
INSERT AccountReceivable (PatientID,PresentCharges,PaymentMade,PreviousBalance,BalanceDue,LastPaymentDate,PresentDate)
                    VALUES (913241,0,57,157,100,5/16/2006,DEFAULT)
 
 
GO
 
--sample query

select PatientID,PresentCharges,LastPAymentDate,PresentDate from AccountReceivable

GO

--result

PatientID PresentCharges LastPaymentDate PresentDate

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

913235 451 1900-01-01 00:00:00.000 2006-09-15 12:54:55.297

918035 109 1900-01-01 00:00:00.000 2006-09-15 12:54:55.297

914235 279 1900-01-01 00:00:00.000 1900-01-01 00:00:00.000

914235 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.297

912224 67 1900-01-01 00:00:00.000 2006-09-15 12:54:55.297

900814 678 1900-01-01 00:00:00.000 1900-01-01 00:00:00.000

900814 0 1900-01-01 00:00:00.000 1900-01-01 00:00:00.000

900814 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.313

913010 203 1900-01-01 00:00:00.000 2006-09-15 12:54:55.313

913010 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.313

913230 1030 1900-01-01 00:00:00.000 2006-09-15 12:54:55.313

918035 78 1900-01-01 00:00:00.000 2006-09-15 12:54:55.313

941235 902 1900-01-01 00:00:00.000 2006-09-15 12:54:55.327

941235 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.327

952235 134 1900-01-01 00:00:00.000 2006-09-15 12:54:55.327

952235 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.327

921635 257 1900-01-01 00:00:00.000 2006-09-15 12:54:55.327

921635 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.327

915235 1204 1900-01-01 00:00:00.000 2006-09-15 12:54:55.327

915235 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.327

900035 578 1900-01-01 00:00:00.000 2006-09-15 12:54:55.343

900035 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.343

913241 157 1900-01-01 00:00:00.000 2006-09-15 12:54:55.343

913241 0 1900-01-01 00:00:00.000 2006-09-15 12:54:55.343

(24 row(s) affected)

 

View 6 Replies View Related

Compare Dates In The Same Record

Jan 9, 2008



I need to compare several dates in a single record and determine the maximum value. Not sure how to do this in TSQL. Something like this (though I obviously can't use the MAX function because):

SELECT MAX(datefield1,datefield2,datefield3) as latestchange,jobnum
FROM table1



Anyone have a function that will do this? Or is there one built in?

Thanks!
Brian

View 11 Replies View Related

Inserting A New Record

Jan 29, 2005

I want to insert a new record into my db in asp.net. Im programming in vb and using an sql server database. i know this is a begginers question but that's exactly what i am. Thanks in advance

View 1 Replies View Related

Retrieve Last Record For Each Month Between Two Dates

Oct 10, 2013

I need to retrieve the last record for each month between two given dates from a unique table that contains on record per day.

View 3 Replies View Related

Inserting A New Record Into A Database.

Oct 30, 2006

hey everyone,I have created two tables in an sql server database. I have a check box in the table 1, and when it is checked, I want to insert that particular record into table 2. (By the way I am using a datagrid) The problem is when I click the check on the particular record I want inserted, and click update, the system copies the record twice instead of once. When I look into table 2, I end up having two of the same records. Can anyone help me.

View 4 Replies View Related

Inserting Null Into A Record

Sep 8, 2007

I am simply trying to use SQLCommand in .net to insert a record into a SQL Server 2005 table. There are 2 fields being pulled from a user input for that could have no values selected. In this case I want to insert a null value into the record. I get an error that Null is no longer supported and that I should use System.DBNull, but that can't be used as an expression.
 How do I do this?
Thank you in advance.

View 1 Replies View Related

Inserting New Record In Sql Server

Jan 8, 2008

 Hi All,   i am new to programming, in my application i want to insert a record in sql server database using Ado.net for that i used    SqlConnection cn=new SqlConnection(ConfigurationManager.ConnectionStrings["constring"].ConnectionString);    SqlCommand cmd;  protected void btnInsert_Click(object sender, EventArgs e)    {      try      {        cmd = new SqlCommand("Insert into DeptInfo(deptid,deptname)values(" + TextBox1.Text + ",'" + TextBox2.Text + "')", cn);        SqlDataAdapter da = new SqlDataAdapter(cmd);        cn.Open();        cmd.ExecuteNonQuery();        cn.Close();        TextBox1.Text = "";        TextBox2.Text = "";      }      catch(Exception ex)     {    }}                But my requirement is when ever the Insert command is successfull it has to display some alert message(using java script) saying  "RECORD INSERTED SUCCESSFULLY"     if   Record insertion  fails it  should display some alert message "INSERTING NEW RECORD FAILED"  .    Any help will be greatly appreciated Thanks,Vision.     

View 15 Replies View Related

Inserting More Than One Record To A New Table

Oct 11, 2004

i am running a query from one of my asp.net pages. I then want the results which will be around 20 - 30 records to be inserted to a new table. How do I do this?

I get the records from my query but how would i insert more than one record to a new table?

thanks

View 4 Replies View Related

Checking To See If A Record Exists Before Inserting

Feb 14, 2007

I can't seem to get this work.  I'm using SQL2005
I want to check if a record exists before entering it.  I just can't figure out how to check it before hand.
Thanks in advance. Protected Sub BTNCreateProdIDandName_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BTNCreateProdIDandName.Click
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand

' Reads the connection string from Web.config
Dim connectionString As String = ConfigurationManager.ConnectionStrings("HbAdminMaintenance").ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)

' Check to see if the record exists
If
comm = New SqlCommand("EXISTS (SELECT (BuilderID, OptionNO FROM optionlist WHERE (BuilderID = @BuilderID) AND (OptionNO = @OptionNO)", conn)

Then
'if the record is exists display this message.
LBerror.Text = "This item already exists in your Option List."
Else


'If the record does not exist, add it. FYI - This part works fine by itself.
comm = New SqlCommand("INSERT INTO [OptionList] ([BuilderID], [OptionNO], [OptionName]) VALUES (@BuilderID, @OptionNO, @OptionName)", conn)

comm.Parameters.Add("@BuilderID", System.Data.SqlDbType.Int)
comm.Parameters("@BuilderID").Value = LBBuilderID.Text

comm.Parameters.Add("@OptionNO", System.Data.SqlDbType.NVarChar)
comm.Parameters("@OptionNO").Value = DDLProdID.SelectedItem.Value

comm.Parameters.Add("@OptionName", System.Data.SqlDbType.NVarChar)
comm.Parameters("@OptionName").Value = DDLProdname.SelectedItem.Value

LBerror.Text = DDLProdname.SelectedItem.Value & " was added to your Option List."

Try
'open connection
conn.Open()
'execute
comm.ExecuteNonQuery()
Catch
'Display error message
LBerror.Text = "There was an error adding this Option. Please try again."
Finally
'close connection
conn.Close()
End Try

End If

End Sub  
 

View 8 Replies View Related

Problem Inserting A Record Into A Table

Jan 7, 2008

I am trying to insert a record into a sql server table from a textbox in a form but am getting this error
The name "textbox1value" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: The name "textbox1value" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.Source Error:



Line 33: dim command1 as sqlcommand=new sqlcommand(q1,connection1)
Line 34: command1.connection.open()
Line 35: command1.executenonquery()
Line 36: command1.connection.close()
Line 37: end sub This code is right below. The sub called a() is the one with the problem.
<html>   <head>      <title>      </title>      <script language="vb" runat="server">         sub page_load(sender as object, e as eventargs)            if not page.ispostback then               binddata1()            end if         end sub          sub binddata1()            dim connection1 as new sqlconnection("server=111.111.11.11;uid=aa;pwd=bb;database=cc")            const q as string="select dxid,code from tbltest where date_del is null order by code"            dim command1 as new sqlcommand(q,connection1)            dim dataadapter1 as new sqldataadapter()            dataadapter1.selectcommand=command1            dim dataset1 as new dataset()            dataadapter1.fill(dataset1)            grid1.datasource=dataset1            grid1.databind()         end sub
         sub a(sender as object,e as eventargs)'            response.write(textbox1.text)            dim textbox1value as string            textbox1value=textbox1.text            dim connection1 as sqlconnection=new sqlconnection("server=111.111.11.11;uid=aa;pwd=bb;database=cc")            const q1 as string="insert into tbltest(code,descriptor) values (textbox1value,'test')"            dim command1 as sqlcommand=new sqlcommand(q1,connection1)            command1.connection.open()
            command1.executenonquery()
           command1.connection.close()         end sub      </script>   </head>   <body>      <form runat="server">         <asp:textbox id="textbox1" runat="server" />         <asp:button id="button1" text="click" onclick="a" runat="server" />         <asp:datagrid id="grid1" runat="server" />      </form>   </body></html>
What am I doing wrong?
 How can I get the insert query to put the value of textbox1.text into the column called code?
Sorry if I am not explaining things clearly. This is like a foreign language to me.
 

View 8 Replies View Related

Check For Primary Key Before Inserting New Record

May 17, 2005

Hi,
Can someone please tell me the best practices for checking the primary key field before inserting a record into my database?
As an example I have created an asp.net page using VB with an SQL server database.  The web page will just insert two fields into a table (Name & Surname into the Names table).  The primary key or the Names table is "Name".   When I click the Submit button I would like to check to ensure there is not a duplicate primary key.  If there is return a user friendly message i.e. A record already exisits, if there no duplicate, add the record.
I guess I could use try, catch within the .APSX page or would a stored procedure be better?
Thanks
Brett

View 7 Replies View Related

DTS - Test Record Integrity Before Inserting

Oct 24, 2000

Is there a way to test the integrity of a record which is about to be inserted in a database before doing so?
The goal is to prevent all kinds of runtime errors that will occur after the insertion, if the record breaks any of the database rules.
The solution should apply to a VBScript used inside a DTS package.

View 3 Replies View Related

Comparing Values And Inserting A Record

Apr 25, 2007

SELECTIndustry,
100.0 * SUM(CASE when ceoischairman = 'yes' then 1 else 0 end) / COUNT(DISTINCT CompID) AS [YesPercent],
100.0 * SUM(CASE when ceoischairman = 'no' then 1 else 0 end) / COUNT(DISTINCT CompID) AS [NoPercent]
FROMTCompanies
GROUP BYIndustry
ORDER BYIndustry

This code above is working as I need it but I need to insert some additional functionality. Thanks

I need to add something like this:

IF YesPercent > NoPercent
UPDATE tableX SET CEOIsChairman='Yes' WHERE Industry='<the industry value being evaluated>'
Else If NoPercent > YesPercent
UPDATE tableX SET CEOIsChairman='No' WHERE Industry='<the industry value being evaluated>'
Else
UPDATE tableX SET CEOIsChairman='Equal' WHERE Industry='<the industry value being evaluated>'
End

View 1 Replies View Related

Inserting Multiple Entries Against 1 Record

Jan 17, 2008

Hi All,

I'm using Microsoft SQL Server Management Studio with SQL Server 2005 (SP2).

I have not had much experience with t-SQL and iterative logic implementation through SQL, therefore I think my problem is fairly basic for most of the pros here.

Here it goes...

I have two tables at hand, TestTab1 and TestTab2.

TestTab1 contains two attributes (columns) namely account_name (nvarchar(50)) and entry_count (int). For all rows in TestTab1, account_name is unique, i.e. for each account_name there is only 1 row in TestTab1. This is my source table.

TestTab2 contains one attribute namely account_name (nvarchar(50)). This table is empty and is my destination table.

I need to insert X entries (rows) for each account_name into TestTab2 where X is the int value in entry_count againt each account_name in TestTab1.

In other words, I need to insert account_name into TestTab2 as many times as the number in entry_count indicates.

I tried reading through the documentation but the help was not friendly enough for me to understand how to implement this.

Looking forward to the pro support.

Thanks,

View 8 Replies View Related

Inserting Carriage Return At The End Of A Record

Jun 15, 2007

Hey everybody!

How do i insert a carriage return at the end of an record that's being sent to a flat file? Currently, I get one long string, and would like for SSIS to put carriage returns at the end of each line.

Any ideas?

Thanks!

Jim Work

View 3 Replies View Related

Inserting A Record Into The Database ..problem With Primary Key..

Sep 7, 2006

hii I have to insert some data into a table from the webpage. For that I need to know the last occurred value in the primary key and increment this by one and then insert the new record into the table. I am working with SQL Server 2005. I am coding in VB and ASP.NET 2.0.  How will I go about this?? Is there some easy way for me to knw the last value of the primary key n then insert the record. It would be great if I get the idea more clear with the help of some code... Thanks

View 2 Replies View Related

Inserting A New Record Into Sql Db Using User-entered Information

Nov 22, 2006

Im trying to add a new rcord to my db on a button click usign the following code
 
'data adapter
Dim dAdapt1 As New SqlClient.SqlDataAdapter
'create a command object
Dim objCommand As New SqlClient.SqlCommand
'command builder
Dim builderT As SqlClient.SqlCommandBuilder
'connection string
Dim cnStr As String = "Data Source=ELEARN-FRM-BETA;Initial Catalog=StudentPlayGround;Integrated Security=True"
'dataset
Dim dsT As DataSet
Private Sub connect()
'connection
objCommand.Connection = New SqlClient.SqlConnection(cnStr)
'associating the builder with the data adapter
builderT = New SqlClient.SqlCommandBuilder(dAdapt1)
'opening the connection
objCommand.Connection.Open()
'query string
Dim query As String = "SELECT * from StudentPlayground..Employees"
'setting the select command
dAdapt1.SelectCommand = New SqlClient.SqlCommand(query, objCommand.Connection)
'dataset
dsT = New DataSet("Trainee Listings")
dAdapt1.Fill(dsT, "Employees")
End Sub
Private Sub BindData()
connect()
DataBind()
End Sub
Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click
Dim empID As Integer = CType(FindControl("TextBox8"), TextBox).Text
BindData()
Dim firstName As String = CType(FindControl("TextBox1"), TextBox).Text
BindData()
Dim lastName As String = CType(FindControl("TextBox2"), TextBox).Text
BindData()
Dim location As String = CType(FindControl("TextBox3"), TextBox).Text
BindData()
Dim termDate As Date = CType(FindControl("TextBox4"), TextBox).Text
BindData()
Dim hireDate As Date = CType(FindControl("TextBox7"), TextBox).Text
BindData()
Dim dept As String = CType(FindControl("TextBox5"), TextBox).Text
BindData()
Dim super As String = CType(FindControl("TextBox6"), TextBox).Text
BindData()
Dim newRow As DataRow = dsT.Tables("Employees").NewRow
newRow.BeginEdit()
newRow.Item(0) = empID
newRow.Item(1) = firstName
newRow.Item(2) = lastName
newRow.Item(3) = location
newRow.Item(4) = hireDate
newRow.Item(5) = termDate
newRow.Item(6) = dept
newRow.Item(7) = super
newRow.EndEdit()
 
'do the update
Dim insertStr As String = "INSERT INTO Employees" + _
"(EmployeeID,FirstName,LatName,Location,HireDate,TerminationDate,Supervisor)" + _
"VALUES (empID,firstName,lastName,location,hireDate,termDate,dept,super)"
Dim insertCmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(insertStr, objCommand.Connection)
dAdapt1.InsertCommand() = insertCmd
 
dAdapt1.Update(dsT, "Employees")
'Dim insertCmd As new SqlClient.SqlCommand = (builderT.GetInsertCommand()).ToString())
'dAdapt1.InsertCommand = New SqlClient.SqlCommand(insertCmd.ToString(), objCommand.Connection)
BindData()
objCommand.Connection.Close()
objCommand.Connection.Dispose()
End Sub
 
im not sure wats going wrong because the record is not being added. Please help!!

View 4 Replies View Related

Inserting A Record For Each Separate Aggregate (solved)

Jul 23, 2005

Hi,As I wrote my message the solution came to me, so I thought I wouldpost anyway for others to see in case it was useful:Here is some sample DDL for this question:CREATE TABLE Source (my_value INT NOT NULL )GOINSERT INTO Source VALUES (1)INSERT INTO Source VALUES (2)INSERT INTO Source VALUES (3)GOCREATE TABLE Destination (value_type VARCHAR(10) NOT NULL,value INT )GOI would like to fill the destination with a row for the COUNT, SUM,MIN, and MAX. My own problem is of course much more complex than this,but this is the basic stumbling block for me now. So, the rows that Iwould expect to see in Destination are:value_type value---------- -----COUNT 3SUM 6MIN 1MAX 3The solution that I came up with was to add a Value_Types table:CREATE TABLE Value_Types (value_type VARCHAR(10) NOT NULL )GOINSERT INTO Value_Types VALUES ('COUNT')INSERT INTO Value_Types VALUES ('SUM')INSERT INTO Value_Types VALUES ('MAX')INSERT INTO Value_Types VALUES ('MIN')GONow the SQL is pretty simple:SELECT V.value_type,CASE V.value_typeWHEN 'COUNT' THEN COUNT(*)WHEN 'SUM' THEN SUM(S.my_value)WHEN 'MAX' THEN MAX(S.my_value)WHEN 'MIN' THEN MIN(S.my_value)ENDFROM Source SINNER JOIN Value_Types V ON 1=1-Tom.P.S. - I know that I did not include primary or foreign keys in my DDL.I'll leave it as an excercise to the reader to figure those out. Ithink the code adequately explains the concept.

View 3 Replies View Related

Inserting A Record Using Values From Another Stored Procedure

Aug 2, 2006

Hello, I'm trying to accomplish 3 things with one stored procedure.I'm trying to search for a record in table X, use the outcome of thatsearch to insert another record in table Y and then exec another storedprocedure and use the outcome of that stored procedure to update therecord in table Y.I have this stored procedure (stA)CREATE PROCEDURE procstA (@SSNum varchar(9) = NULL)ASSET NOCOUNT ONSELECT OType, Status, SSN, FName, LNameFROM CustomersWHERE (OType = 'D') AND (Status = 'Completed') AND (SSN = @SSNum)GO.Then, I need to create a new record in another table (Y) using the SSN,FName and Lname fields from this stored procedure.After doing so, I need to run the second stored procedure (stB) Here itis:CREATE PROCEDURE procstB( @SSNum varchar(9) = NULL)ASSET NOCOUNT ON-- select the recordSELECT OrderID, OrderDate, SSNFROM OrdersGROUP BY OrderID, OrderDate, SSNHAVING (ProductType = 'VVSS') AND (MIN(SSN) = @SSNum)GO.After running this, I need to update the record I created a moment agoin table Y with the OrderDate and OrderID from the second storedprocedure.Do you guys think that it can be done within a single stored procedure?Like for example, at the end of store procedure A creating an insertstatement for the new record, and then placing something like execprocstB 'SSN value'? to run stored procedure B and then having aupdate statement to update that new record?Thanks for all your help.

View 1 Replies View Related

Inserting Record Setting INDENTITY_INSERT ON With Replication

May 16, 2008



A user inadvertantly deleted a record in a table that maintains an identity seed. I attempted to insert the record using SET IDENTITY_INSERT ON, but forgot that this table is an article in merge replication. I am attempting the insert on the publisher and I get the following message:


Msg 548, Level 16, State 2, Line 2

The insert failed. It conflicted with an identity range check constraint in database 'cad', replicated table 'dbo.emmain', column 'empl_id'. If the identity column is automatically managed by replication, update the range as follows: for the Publisher, execute sp_adjustpublisheridentityrange; for the Subscriber, run the Distribution Agent or the Merge Agent.

The statement has been terminated.


How can I re-insert this record??Thanks in advance for any help

View 2 Replies View Related

SQL Server 2012 :: Find Most Recent Record Of Consecutive Dates

Feb 23, 2015

I have a table full of service invoice records. Some of the invoices are continuous, meaning that there may be an invoice from 01-16-2015 through the end of that month, but then another invoice that starts on feb 1 and goes for 6 months.

I want to only pull the most recent. Keep in mind that there may be other invoices in the same table for a different period. An example might be:

FromDate ToDate Customer Number Contract Number
02/01/2015 07/31/2015 2555 456
01/15/2015 01/31/2015 2555 456
04/01/2013 09/30/2015 2555 123
03/13/2013 03/31/2013 2555 123

From this table, I would like a query that would give me this result:

01/15/2015 07/31/2015 2555 456
03/13/2013 09/30/2015 2555 123

There will likely be more than just 2 consecutive records per contract number.

View 4 Replies View Related

To Display An Alert Message While Inserting A Duplicate Record

Dec 21, 2005

I am duplicating a record from my asp.net page in to the database. When i click on save I am getting the following error message
Violation of PRIMARY KEY constraint 'PK_clientinfo'. Cannot insert duplicate key in object 'clientinfo'. The statement has been terminated.
The above message i am getting since i have tried to duplicate the clientname field of my table which is set as the primary key.
What i want is instead of this message in the browser i need to display an alert saying "the clientname entered already exists" by checking the value from the database.
Here is my code. pls modify it to achieve the said problem
if(Page.IsValid==true)    {           conn.Open();     SqlCommand cmd = new SqlCommand("insert into clientinfo (client_name, address) values ('"+txtclientname.Text+"', '"+txtaddress.Text+"')", conn);     cmd.ExecuteNonQuery();     conn.Close();     BindData();     txtclear();      System.Web.HttpContext.Current.Response.Write("<script>alert('New Record Added!');</script>");     Response.Redirect("Clientinfo.aspx");    }

View 1 Replies View Related

Geting Timeout Error In Application When Inserting Record

Mar 9, 2006

i currently have more tha 3 million of records in my table in sql 7. i am getting timeout error in my web application when i try to insert a record in that table

what could be rhe reason for this? how to avoid this type of problem?

Thanks in advance

View 1 Replies View Related

Question On Inserting A Record On Sql Server With Identity Column As Key

Jan 16, 2006

Hi, All:Please help. I use sql server as back end and Access 2003 as front end(everything is DAO).A table on SQL server has an identity column as the key.We have trouble on adding records to this table using the following SQL.strSQL = "INSERT INTO myTableOnSQLServer (A, B, C, D, E) SELECT A, B, C, D,E FROM myTableonAccessLocal"db.execute strSQLThe schema of the table "myTableOnSQLServer" and the schema of the table"myTableonAccessLocal" are all the same except that the "myTableOnSQLServer"has an identity column (ID). The key of the "myTableOnSQLServer" is "ID" andthe table "myTableonAccessLocal" does not have a key.When we try to run the query, it gives errors indicating the key is violatedor missing.Should I figure out the autonumber for it first and then add to the SQLserver table?Many thanks,HS

View 1 Replies View Related

SQL Server 2012 :: Inserting Record In Table - Trigger Error

Aug 6, 2014

I am inserting a record in XYZ table(DB1). Through trigger it will update ABC table(DB2).

I am getting error when doing above thing. What are the roles to be set to user to avoid above problem.

View 3 Replies View Related

Problem In Inserting A Record Whose Values Are Of Date And Time Format.

Jan 11, 2007

hello,

I am trying to insert date and time into my table.

insert into <table_name> values('12/12/2006','12:23:04');

but it displays error at " ; "

can anyone help me to figure out the problem



Thanks a lot in advance.

Regards,

Sweety

View 3 Replies View Related







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