Help With Add, Update Or Deleting A Record

Feb 27, 2006

Hi SQL gurus,

I have a form that depending on the outcome, will either add, update or delete a record.

1) If there IS NO record of "this" and "that" and Request("x") <> "" it will add a new record.

2) If there IS a record for "this" and "that" and Request("x") <> "" it will update column 1,2,3 or 4.

3) If there is a record for "this" and "that" and Request("x") = "" it will delete the record.

My problem is if there is a value in request("1") it works fine, but if there is no value in ("1") and there is a value in 2, 3, or 4 it will delete the record.


If request("1") <> "" OR request("2") <> "" OR request("3") <> "" OR request("4") <> "" Then

sSQL = "SELECT * FROM some_column WHERE this = '" & request("this) & "' and that = '" & request("that) & "'"
oRS.Open sSQL,oConn,adOpenKeySet,adLockOptimistic
If oRS.EOF Then
oRS.Addnew
oRS.Fields("this") = request("this")
ors.Fields("that") = request("that")
Else
ors.Movefirst
End If
oRS.fields("1") = request("1")
oRS.fields("2") = request("2")
oRS.fields("3") = request("3")
oRS.fields("4") = request("4")
oRS.Update
oRS.Close

Else

sSQL = "Delete from some_table Where this = '" & '" & request("this) & "' & "' AND that = '" & '" & request("that) & "' & "'"
objCmd.ActiveConnection = oConn
objCmd.CommandType = adCmdText
objCmd.CommandText = sSQL
objCmd.Execute

End if

Hope I explained that okay.

View 1 Replies


ADVERTISEMENT

Deleting A Record

Oct 9, 2007

I have three tables
1. membership table(aspnet_membership table)
2. User Contacts table
3. Address table
These three table have relation ship with one another through a UserId field. 
How will you set up cascaded delete on these tables, Like if I delete a user in the membership table I want the related records in the other tables to be deleted as well. Cascaded delete is it something done through code, or is it definde when the tables are created.
Please advice. 
 

View 1 Replies View Related

Deleting All But Top Record.

Jun 23, 2005

Hey Guys,I have Performance Monitor running and storing the network usage to my MsSQL database, and this is done a few times a minute. I have a page that then shows show much of my bandwidth is being used. As you can gather, the database quickly starts filling up with hundrreds of records so I could do with a script that delete these records. I cant simply delete all records because that would cause my webpage to fail so I need a way to delete all records apart from the latest one. Wondering if anyone would know how I could do this?

View 3 Replies View Related

Deleting Duplicate Record

Nov 19, 2004

hi to all,

How to delete duplicate record in the recordset?

Thanks...

View 3 Replies View Related

Deleting A Record From A VIEW

Jul 20, 2005

Hi All,I am using Microsoft SQL Enterprise Manager version 8.0 and havecreated a view from a combination of 4 different tables. I would liketo be able to go into sql and open the view and select a row anddelete that row however this seem impossible right now. I am not sureif it's possible to delete a row from a view?? Or could it be thatthese tables are all interconnected and in order to delete a recordthat is joined to one or more of the tables it has to be deleted atthe top level of the join heirarchy etc etc. (do you understand what imean?) Can this be done??Thanks in advance,Erin

View 4 Replies View Related

Problem In Deleting A Record From Tale

Nov 25, 2006

hai dears i want to delete a row from the table on the basis of key sent in beusers obj
 
"connection myConn = new connection();" this is ma own class that establishes the connetion which works fine in other caseseg insert
'' it shows no error or exception ' but do not delete record
so plz tell me how to do this...
 or whats wrong in this
public void delete(BEusers obj)
{
connection myConn = new connection();
 oCommand = new SqlCommand("sp_delete_tbl_users_by_userid",myConn.sqlCon);
oCommand.CommandType = CommandType.StoredProcedure;
 
 try {
 myConn.OpenConnection();
 sp = oCommand.Parameters.Add("@User_Id", SqlDbType.VarChar);
 sp.Size = 20;
sp.Value = obj.user_id;
oCommand.ExecuteNonQuery();
 }
catch (Exception oException)
{ throw oException; }
finally { myConn.CloseConnection(); }
 }
 

View 3 Replies View Related

Deleting A Record Older Then 10 Minutes

Aug 26, 2005

Hey Guys,I have been trying to work out how I would delete a record that was created more then 10 minutes ago.I can use this to delete records older then a day.DELETE FROM DownloadQueue WHERE Downloading = '0' AND QueuePos = '0' AND DateTime < GETDATE() - 1Just need something now that will do it for just 10 minutes.Cheers.

View 1 Replies View Related

Deleting The Duplicate Record From Table

Mar 26, 2008

Hi ,
i am using sql server 2005.
i have one table where i need to find records that have same citycode and hospitalcode and doctorcode then delete the record keeping only one record of them
my problem is table structure have idendtity column which is unique.
that is m table structure is something like

recid citycode hospcode doctorcode otherdesp
1 0001 hp001 d0001 ...
2 0002 hp002 d0002 ...
3 0001 hp001 d0001 ...
4 0002 hp002 d0002 ...

please suggest

thank you

View 2 Replies View Related

SqlCeResultSet - Problem After Deleting First Record

Oct 4, 2006



Hi,

I've noticed that after the first record from a ResultSet is deleted, HasRows property throws an exception like "The current row was deleted." Method ReadFirst() throws similar exception as well.

More details:

1. Create a ResultSet: ExecuteResultSet(ResultSetOptions.Updatable | ResultSetOptions.Scrollable | ResultSetOptions.Sensitive)

2. Let's say, there is no records in the resultset. Insert two new ones. Then call: ReadAbsolute(0); Delete(); HasRows; and the exception is thrown.

3. Then you can call ReadFirst() or Read with the same result.

4. Now call ReadAbsolute(0). It returns true. Call HasRows, ReadFirst() or Read() and you will get the exception each time.

I tried to explain this with the fact that Delete() doesn't change the current position of the ResultSet. But I don't see why that would mess the HasRows property or why after ReadAbsolute(0) retuns true, HasRows or ReadFirst() doesn't work.

Could anybody tell me what the problem is?

Thank you.

View 7 Replies View Related

SqlCeResultSet - Problem After Deleting First Record

Oct 3, 2006

Hi,

I've noticed that after the first record from a ResultSet is deleted, HasRows property throws an exception like "The current row was deleted."   Method ReadFirst() throws similar exception as well.

More details:

1. Create a ResultSet: ExecuteResultSet(ResultSetOptions.Updatable | ResultSetOptions.Scrollable | ResultSetOptions.Sensitive)

2. Let's say, there is no records in the resultset.  Insert two new ones.  Then call: ReadAbsolute(0); Delete(); HasRows; and the exception is thrown.

3. Then you can call ReadFirst() or Read with the same result.

4. Now call ReadAbsolute(0).  It returns true.  Call HasRows, ReadFirst() or Read() and you will get the exception each time.

I tried to explain this with the fact that Delete() doesn't change the current position of the ResultSet.  But I don't see why that would mess the HasRows property or why after ReadAbsolute(0) retuns true, HasRows or ReadFirst() doesn't work.

Could anybody tell me what the problem is?

Thank you.

 

View 1 Replies View Related

Creating A Trigger To Check Before Deleting A Record

Jun 12, 2008

I am using the tables created by the aspnet_regsql.exe tool for security.  Basically, I need to ensure that an account named Administrator is never deleted.  I also have a role named administrator, and I need to make sure that Administrator is never removed from the administrator role.Can I create a trigger to ensure that the Administrator is never deleted and that the Administrator is never removed from the Administrator role?  I know it will probably be two separate triggers: one on the aspnet_users table and one on the aspnet_usersinroles table.Thanks a lot for the help!

View 1 Replies View Related

Stored Procedure For Deleting A Record With Contstraints (m:n)

Oct 9, 2007

I can not get this stored procedure to delete my records...

I have a
contact table
RecordID
FirstName
LastName
etc

and a Address table

RecordID
Street
Zip
Town
Country

And a Relation table

RecordID
ContactID
AddressID
CreateDate


set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[bc_Contact_Delete]

@ContactID int

AS

--SET NOCOUNT ON

BEGIN TRY

BEGIN TRANSACTION -- Start the transaction



-- Delete all Adresses

DELETE FROM [Address]

WHERE

RecordId in (SELECT ca.AdressId from [ContactAddress] ca

where

ca.ContactID = @ContactID)

-- Delete all Relations

DELETE FROM [ContactAdress]



WHERE ContactID = @ContactID

--- Delete Kontakt

DELETE FROM [Contact] WHERE (([RecordId] = @ContactID))

COMMIT TRANSACTION

END TRY

BEGIN CATCH

-- Whoops, there was an error

ROLLBACK TRANSACTION

-- Raise an error with the

-- details of the exception

DECLARE @ErrMsg nvarchar(4000),

@ErrSeverity int

SELECT @ErrMsg = ERROR_MESSAGE(),

@ErrSeverity = ERROR_SEVERITY()



RAISERROR(@ErrMsg, @ErrSeverity, 1)

END CATCH

RETURN


My Errormessage is

The DELETE statement conflicted with the REFERENCE constraint "FK_bc_ContactAdress_bc_Address". The conflict occurred in database "bContacts", table "dbo.ContactAddress", column 'AdressID'.

Can someone please post me an advice?

View 5 Replies View Related

Timeout Errror When Deleting A Record From SQL Server Through MS Access

Mar 11, 1999

I can't delete records for a SQL Server table when I attached the table to Microsoft Access 97. I time out when I try to delete the record. However I can query the table.

I use the standard ODBC setup, do I need to do anything else beside using the standard Access link.

Thanks in advance

View 1 Replies View Related

Possible To Avoid The FILLING Of GAP (created By Deleting A Record) In The Identity Column ?

Jun 18, 2007

Hi all,
(I am using SQL Server 2005)
I have created a new 'CUSTOMERS' table and created a colum 'CustomerID' as an Identity column.
Now, a problem I find is that when I delete a particular record, its Identity value is used automatically for the New record I insert later!
I do not want to re-use the already used Identity value.
I just want to have the last CustomerID to be higher that all the previous ones.
Is there any way to do this?
Thanking you in advance,
Tomy

View 2 Replies View Related

Update A Record Based Of A Record In The Same Table

Aug 16, 2006

I am trying to update a record in a table based off of criteria of another record in the table.

So suppose I have 2 records

ID owner type

1 5678 past due

2 5678 late

So, I want to update the type field to "collections" only if the previous record for the same record is "past due". Any ideas?

View 5 Replies View Related

Lookup &&amp; Update Record &&amp; Insert Record

Mar 26, 2008

Hi All,

I am trying to create package something like that..

1- New Customer table as OleDB source component
2- Lookup component - checks customer id with Dimension_Customer table
3- And if same customer exist : I have to update couple fields on Dimension_Customer table
4- if it does not exist then I have insert those records to Dimension_Customer table

I am able to move error output from lookup to Dimension_Customer table using oledb destination
but How can I update the existing ones?
I have tried to use oledb command but somehow it didnt work
my sql was like this : update Dimension_Customer set per_X='Y', per_Y= &Opt(it should come from lookup)

I will be appreciated if you can help me...

View 3 Replies View Related

Problem With ID Update After Deleting Rows

Jul 18, 2007

Hi,



I hope some of you can help me with that



I made an application that insert some data to MS SQL 2005 DB Express Edition. One of columns in my database store text. The content of that field must, beyond the existing text, append the current id to its text string. Practically, it means that if on row nr 15 I store text value "15text", on the next row i will store "16text". I figured out that I can get value of max ID by creating following stored procedure.

USE [tracking_db]

GO

/****** Object: StoredProcedure [dbo].[spMaxId] Script Date: 07/18/2007 09:31:44 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[spMaxId]

@maxId integer output

as

SELECT @maxId= MAX(id) FROM FILES_TABLE





Once i get the maxID value i simply concat max id and string like:



string.Concat(max_id.ToString(), file_name);



where "max_id is integer return value from stored procedure and "file_name" is a string to rename like "max_id+file_name"





Two problems occur!!!

Problem nr 1.



Since I use to insert 10 new rows each time, the values from 0-9 are appended to text like "(0-9)text"



Problem nr 2.



If I delete some rows, ID does not get update. It means that after deleting all rows from table, next inserted item gets last existed ID before delting +1. New inserted item should get value 1 since table is empty after deleting all rows from it!!!



Hope some of you has any idea what to do



Muris

View 6 Replies View Related

Trigger To Update One Record On Update Of All The Tables Of Database

Jan 3, 2005

hi!

I have a big problem. If anyone can help.

I want to retrieve the last update time of database. Whenever any update or delete or insert happend to my database i want to store and retrieve that time.

I know one way is that i have to make a table that will store the datetime field and system trigger / trigger that can update this field record whenever any update insert or deletion occur in database.

But i don't know exactly how to do the coding for this?

Is there any other way to do this?

can DBCC help to retrieve this info?

Please advise me how to do this.

Thanks in advance.

Vaibhav

View 10 Replies View Related

Update Statement - Deleting Oldest Date

Sep 17, 2014

I have a table that I need to delete the oldest date. I thought I could just do an update statement saying...

Delete T_BreakDown
where Date = MIN(Date)

But that doesn't work.

View 4 Replies View Related

Deleting The Master Table Withour Deleting The Child Tables

Aug 9, 2007

Hi
i have to delete the master table data without deleting the child table records,is there any solution for this,  parent table has relation with the child table.
regards
vinod.t.v

View 9 Replies View Related

T-SQL (SS2K8) :: Deleting Only 1 Row At A Time Instead Of Using Condition And Deleting Many Rows?

Jul 18, 2014

/****** Object: StoredProcedure [dbo].[dbo.ServiceLog] Script Date: 07/18/2014 14:30:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[ServiceLogPurge]

-- Purge records dbo.ServiceLog older than 3 months:
-- Purge records in small portions to avoid locking production tables
-- for a long time. The process takes longer, but can co-exist with
-- normal usage of the tables.

[Code] ...

*** Getting this error below when executing the code ***

Msg 102, Level 15, State 1, Procedure ServiceLogPurge, Line 45
Incorrect syntax near 'Failed:'.

View 9 Replies View Related

Update Record

Jun 6, 2007

I am looking for some guidence on the following.
when i click the save button, The record should be updated to the table. I have produced the code below which does'nt seem to work. Please guide me
It works fine when i hard code the value for "textbox value" in line    SqlDataSource1.UpdateParameters.Item("PrmVal").DefaultValue = "Textbox value"
 Protected Sub SaveRecord(ByVal sender As Object, ByVal e As System.EventArgs)       If Page.IsValid Then                                    SqlDataSource1.UpdateParameters.Item("PrmVal").DefaultValue = Textbox value            SqlDataSource1.Update() end ifend sub
<form id="form1" runat="server">    <div>        &nbsp;</div>        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:BmsConnectionString %>"                    SelectCommand="SELECT [PrmGrp], [PrmCde], [PrmVal], [PrmValArb], [GrpDsc] FROM [PrmDef] WHERE (([PrmGrp] = @PrmGrp) AND ([PrmCde] = @PrmCde))"        UpdateCommand="UPDATE PrmDef SET  PrmVal=@PrmVal, PrmValArb=@PrmValArb, GrpDsc=@GrpDsc,RecSts=1 WHERE (([PrmGrp] = @PrmGrp) AND ([PrmCde] = @PrmCde))">                    <SelectParameters>                <asp:QueryStringParameter   Name="PrmGrp" QueryStringField="PrmGrp" Type="String" />                <asp:QueryStringParameter   Name="PrmCde" QueryStringField="PrmCde" Type="String" />                                            </SelectParameters>                        <Updateparameters>                   <asp:parameter Name="PrmGrp"   />                <asp:parameter Name="PrmCde"  />                                <asp:parameter Name="PrmVal"  />                <asp:parameter Name="PrmValArb"   />                <asp:parameter Name="GrpDsc" />                   <asp:parameter Name="RecSts" />                </Updateparameters>                    </asp:SqlDataSource>        <asp:FormView ID="FormView1" runat="server" DataKeyNames="PrmGrp,PrmCde"            DataSourceID="SqlDataSource1" DefaultMode="Edit" Width="670px" style="left: 12px; position: relative; top: 12px; z-index: 100;" Height="359px" BorderStyle="Double" BorderWidth="5px" CaptionAlign="Top" GridLines="Both" BorderColor="Maroon" CellPadding="2">            <EditItemTemplate>                <br />                Parameter Group:                <asp:Label ID="PrmGrp" runat="server" Text='<%# Eval("PrmGrp") %>' style="left: 34px; position: relative; top: 0px" Width="125px"></asp:Label><br />                <br />                Parameter Code:                <asp:Label ID="PrmCde" runat="server" Text='<%# Eval("PrmCde") %>' style="left: 40px; position: relative; top: 0px" Width="125px"></asp:Label>                <br />                <br />                English description: &nbsp;                <asp:TextBox ID="PrmValTextBox" runat="server" Text='<%# Bind("PrmVal") %>' style="left: 17px; position: relative; top: 0px" Width="318px"></asp:TextBox>&nbsp;                                <br />                Arabic description:                <asp:TextBox ID="PrmValArbTextBox" runat="server" Text='<%# Bind("PrmValArb") %>' style="left: 25px; position: relative; top: 0px" Width="317px"></asp:TextBox><br />                <br />                Group description:                <asp:TextBox ID="GrpDscTextBox" runat="server" Text='<%# Bind("GrpDsc") %>' style="left: 29px; position: relative; top: 4px" Width="316px"></asp:TextBox><br />                <br />                &nbsp;                <asp:Button ID="CmdSave" runat="server" OnClick="SaveRecord" Style="left: 134px; position: relative; top: 49px"                    Text="Save" Width="72px" />&nbsp;                <asp:Button ID="CmdDelete" runat="server" OnClick="DeleteRecord"  Style="left: 145px; position: relative; top: 50px"                    Text="Delete" Width="79px"  />                <asp:Button ID="CmdClose" runat="server" OnClick="CloseWindow" Style="left: 160px; position: relative; top: 48px"                    Text="Close" Width="73px" /><br />                <br />                <asp:Label ID="ErrLabel" runat="server" Font-Bold="True" Font-Size="Small" ForeColor="#C00000"                    Style="left: 148px; position: relative; top: -38px" Text="Fields marked as (*) are required"                    Visible="False" Width="318px"></asp:Label><br />            </EditItemTemplate>                             <ItemTemplate>                PrmGrp:                <asp:Label ID="PrmGrpLabel" runat="server" Text='<%# Eval("PrmGrp") %>'></asp:Label><br />                PrmCde:                <asp:Label ID="PrmCdeLabel" runat="server" Text='<%# Eval("PrmCde") %>'></asp:Label><br />                PrmVal:                <asp:Label ID="PrmValLabel" runat="server" Text='<%# Bind("PrmVal") %>'></asp:Label><br />                PrmValArb:                <asp:Label ID="PrmValArbLabel" runat="server" Text='<%# Bind("PrmValArb") %>'></asp:Label><br />                GrpDsc:                <asp:Label ID="GrpDscLabel" runat="server" Text='<%# Bind("GrpDsc") %>'></asp:Label><br />            </ItemTemplate>            <HeaderStyle BorderStyle="Double" BackColor="#FFC0C0" BorderWidth="5px" BorderColor="Black" HorizontalAlign="Center" VerticalAlign="Middle" />            <HeaderTemplate>                Business parameter(Edit)            </HeaderTemplate>            <RowStyle BorderWidth="5px" />        </asp:FormView>        &nbsp;&nbsp;&nbsp;&nbsp;    </form>

View 4 Replies View Related

Not Able To Update A Record!

Jul 18, 2007

Hi everybody,I am using SQL Server 2005. I have a table which currently has only 1 record. I am unable to update any field for this particular record and SQL server is timing out and giving an error message saying No row was updated. I created another record in the table and tried to update the fields in the new record without any problem. I am unable to update any field only for the 1 record in the table using my application, query window sql statement as well as directly changing the in the database.Can anybody please help me.thanks in advance,Murthy here 

View 3 Replies View Related

Update With Top 1 Record

May 15, 2008

I am in a situation in which I would like to update my one table three column with other table three column, The other table might have more then one record but I would like to have the TOP 1 record of that table for these column. How can I achive it. I know I will be able to achive by writing three statment like
Update abc
set a=(select top 1 a from xyz order by ),
b=( select top 1 b from xyz) and so but not sure that a and b using the same record and thats the requirment of update is
any help much apprecited

View 1 Replies View Related

Update Only One Record

Jul 23, 2005

Hello,update table set column = x where b is nullI have the above update statement in a transact sql file. I would liketo change it so that it will only update 1 of the records in the table,even if there are many records where b is null....Any ideas would be great.Many thanks,Allan

View 1 Replies View Related

How To Update Just One Record

Jul 23, 2005

HiI've a table with 2 columns, one for a client code and one for adate/time and could be more than one record with the same client codeand date/time. the 3rd column is another date/time, NULL by default.I need to check if exists records for a determinated client code anddate/time and place the current date/time in the 3rd column for just oneand only one record.Is this possible ? How ?Thanks in advanceJ

View 9 Replies View Related

How To Update A Record??

Feb 1, 2008



I'm very surprised since I cannot do a simple update operation...

Seems that the cursor after a Read, Readfirst, ReadLast or ReadPrevious is gone...

Here is a possible sequence from the user's standpoint.


1) Performs a QBE search


cmd_Logbook_search = Conn_User.CreateCommand()

cmd_Logbook_search.CommandText = sql_Logbook

rset_Logbook = cmd_Logbook_search.ExecuteResultSet(ResultSetOptions.Updatable Or ResultSetOptions.Scrollable)

-----

If rset_Logbook.HasRows = False Then Exit Sub



rset_Logbook.ReadFirst()

Me.Fill_Logbook_TextBoxes()


2) Navigates


Try

If True = rset_Logbook.Read() Then
Me.Fill_Logbook_Textboxes()
Else

rset_Logbook.ReadLast()

Me.Fill_Logbook_Textboxes()

End If

Catch ex As Exception ' esta excepción se levanta si el recordset está vacio

MessageBox.Show(m11, m1, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)

End Try

3) Update the record


If Result = DialogResult.Yes Then

Try

rset_Logbook.SetValue(rset_Logbook.GetOrdinal("Altitude"), Me.TextBox_Altitude.Text)

rset_Logbook.Update()

MessageBox.Show("OK", m1, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)

Catch ex As Exception

MessageBox.Show(ex.message, m1, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)

End Try

End If

And I always gets a "No data exist for row/colum" so...where did the cursor gone?

Any help, please I need to move forward! Thanks a lot in advance!!

View 7 Replies View Related

Record Set Update

Jul 10, 2007

Hi
I am new to visual studio and I am attempting to edit records held in mysql, the code below runs and throws no errors "strAdd" is underlined and says that it is used before it has been given a value! But If I debug.print(strAdd) I get the expected string returned. What do I need to do to get the updated records saved?

' code

Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim StrAdd as string

cn = New ADODB.Connection
cn.ConnectionString = "Provider=SQLNCLI;" _
& "Server=(local);" _
& "Database=customerlink;" _
& "Integrated Security=SSPI;" _
& "DataTypeCompatibility=80;" _
& "MARS Connection=True;"
Dim mySQL As String

mySQL = "SELECT *" & _
" FROM tblvsol" & _
" Where RevStatus = " & 0 & _
" And GeoCodeStatus = " & 1

cn.Open()

rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.CursorLocation = ADODB.CursorLocationEnum.adUseClient
.CursorType = ADODB.CursorTypeEnum.adOpenDynamic
.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic
.Open(mySQL)
End With

Do While Not rs.EOF

Code here finds the value for the string variable €˜atrAdd€™

strAdd = New Value


If Not strAdd Is Nothing Then

rs.Fields("location").Value = strAdd
rs.Fields("RevStatus").Value = 1
rs.Update()
else
end if

loop

Regards
Joe

View 9 Replies View Related

How To Update Only One Record

Feb 22, 2008

How do I tell an update query to do the update only to one row in the table, and if there s more than one row in the where clause, then not to do the update.

Something like this:


update top 1 set myCol='value' where searchCol='criteria'


But that causes an error.

View 6 Replies View Related

Cannot Update Record In Database.

May 4, 2004

Hello,

I was stuck when update database using SqlDataAdapter. I have several textboxes in my webform1. When wepform1 is loaded, they will display user's information. The user can only input content in two textboxes. When user clicks the update button, I hope to update this record in SQL Server 2000 database. However, the program didn't work. There was no error message reported but when I stepped into the code, I found out that dataadapter's update method didn't succeed. I got 0 rows affected. Can I get some advice from someone ?

Here is the code:

string StrUpdateCmd = "Update Table1 Set Hphone = @Hphone, Cphone = @Cphone, Team = @Team Where emailname =@emailname ";

SqlDataAdapter UpdateDa = new SqlDataAdapter("Select * from Table1",SqlConnection1);
UpdateDa.UpdateCommand = new SqlCommand(StrUpdateCmd, SqlConnection1);

//Add parameters of update command.
SqlParameter prm1 = UpdateDa.UpdateCommand.Parameters.Add("@Hphone",SqlDbType.NVarChar, 16);
prm1.Value = txtHphone.Text ;

SqlParameter prm2 = UpdateDa.UpdateCommand.Parameters.Add("@Cphone",SqlDbType.NVarChar, 16);
prm2.Value = txtCphone.Text ;

SqlParameter prm3 = UpdateDa.UpdateCommand.Parameters.Add("@Team",SqlDbType.NVarChar, 16);
prm3.Value = this.DropDownList1.SelectedItem.Value ;

SqlParameter prm4 = UpdateDa.UpdateCommand.Parameters.Add("@emailname",SqlDbType.NVarChar, 50);
prm4.Value = txtEmail.Text;

try
{
DataSet dataset2 = new DataSet();

//Open database connection.
SqlConnection1.Open();
dataset2.Clear();
UpdateDa.Fill(dataset2, "Table1");

this.DataGrid1.DataSource = dataset2.Tables[0] ;
DataGrid1.DataBind ();

//Update database
int ret =UpdateDa.Update(dataset2,"Table1");
if( ret == 1 )
{
ShowMessage("Update succeed!");
}
else
{
ShowMessage("There is an error in updating ");
}

UpdateDa.Fill(dataset2);

//Show data after update.
this.DataGrid1.DataSource = dataset2;
DataGrid1.DataBind ();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection1.Close();
}

View 1 Replies View Related

How Can I Retrieve The Id Of A New Record Before Update

Oct 14, 2001

Can anyone help with an effective way in retriving the id of the new record before input of any data into a form. We have a form where a few of the controls recordsource requires the new record id before they will display correctly. I have tried various ways to trigger the form afterupdate event in the hope that the id will be returned but get the error message "The data will be added to the database but the data won't be displayed in the form because it doesn't satisfy the criteria in the underlying recordsource"

Thanks in advance

View 1 Replies View Related

UPDATE Every Record In Table

Jul 12, 2007

This should be incredibly simply but I've been working on it for quite a while and have had no luck:

There's ONE table with many columns but I'm only interested in three columns.

DistrictLEA
SSN

And a third column titled DistrictLEASSN

This is an odd scenario but I need to concatenate DistrictLEA + SSN for each record and update DistrictLEASSN with the result.

Is there a good method to do this with T-SQL/Cursors?

UPDATE DistrictLEASSN
SET DistrictLEASSN= DistrictLEA + SSN

I'd like to loop through each record in the table and perform the operation.

Thanks! -CD

View 6 Replies View Related

Update A Record In Another Db Using A Trigger

Mar 4, 2005

here is my trigger that i have right now the only problem is that it deletes the records before copying everything into the db i dont what do delete everything i just whant to catch the updated record and then update the other tables same record in the other db how would i do this:

right now i have this


CREATE TRIGGER test ON [dbo].[TEST123]
AFTER INSERT, UPDATE, DELETE
AS
IF @@ROWCOUNT = 0
RETURN

IF (COLUMNS_UPDATED() & 2 = 2)
DELETE FROM pubs..TEST123 WHERE test3 = '300'
INSERT INTO pubs..TEST123
SELECT * FROM TEST123 WHERE test3 = '300'
UPDATE pubs..TEST123 SET test1 = 'X' WHERE test1 IS NULL AND test3 = '300'
UPDATE pubs..TEST123 SET test2 = 'X' WHERE test2 IS NULL AND test3 = '300'
UPDATE pubs..TEST123 SET test3 = 'X'

View 2 Replies View Related







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