How To Update If Customer Doesn't Exist (was Help With An Update)

Mar 7, 2005

OK,
This is an Update that I have working, But what do I do, if the customer does not exist already it doesn't add the customer? How should I remedy this? if the customer does exist works great.

UPDATE AC
SET CustId = Left (CustomerId,10),
CustName = Left (CustomerName,25),
Addr1 = Left (Address1,25),
Addr2 = Left (Address2,25),
City = Left (ca.City,15),
Region = Left (State,2),
PostalCode = Left (Zip,5)
FROM RIO.dbo.tblArCust AC INNER JOIN
(SELECT CustomerCode, MAX(LastUpdatedDate) MaxDate
FROM COFFEE.dbo.vueCustomerAddress
GROUP BY CustomerCode) V
ON V.CustomerCode = AC.CustId
INNER JOIN COFFEE.dbo.vueCustomerAddress CA
ON CA.CustomerCode=V.CustomerCode AND
MaxDate=LastUpdatedDate
WHERE CA.addresstypeid = 1

View 1 Replies


ADVERTISEMENT

If Not Exist Insert Else Update

Feb 17, 2014

How do I Use the insert code below only if a record does not exist in the cisect table? Then if it exists I just want to

update cisect
set ml_desc_0 = cus_type_desc
from artypfil_sql A join cisect c on a.cus_type_cd = c.sct_code
INSERT INTO [002].[dbo].[cisect]
([sct_code]
,[ml_desc_0]
,[syscreated]
,[syscreator]

[code]....

View 3 Replies View Related

Formview Doesn't Update

Dec 13, 2006

I have formview and I have a SqlDatasource for it.I have few textboxes in the edit mode and bind it to the data columns or fields in the database.If the data for all those fields have content in it, then it will update just fine. However, if one of the text field is null or empty, the formview can't be updated    When i try to update with empty data in one textboxData field allows null value, and type are varchar.I am suspecting it's throwing an internal exception somewhere. However, since all the operations are handled by the asp.net.  I have no idea what's going on internally. Does anyone have an idea what's causing this error and how to fix it?  

View 2 Replies View Related

Code Doesn't Update SDF

May 31, 2008

In the device emulator when it starts I see two records that were added to the SDF in the VS2008 IDE. I added a third record and after tapping on the Save menu my navigation control shows all three records. I then closed the application. I went to Memory and stopped the form. I went to the File Editor and restarted the application. It only showed the original 2 records. In the File Editor I tapped on the SDF to open it in the Query Analyzer. It also only shows the original two records.

The Dataset appears to be updated, but not the bound table in the SDF. Can any one help? Code is below.
bsTEST is the binding SOurce
navTEST is my custom Navigation control


Private Sub HandleMenus(ByVal Sender As Object, ByVal EA As EventArgs) Handles mnuAdd.Click, mnuCancel.Click, mnuSave.Click

With Me

Select Case True

Case Sender Is .mnuAdd

.Menu = .mnuCancelSave

txtLOC.ReadOnly = False

bsTEST.AddNew()

.navTest.Visible = False

Case Sender Is .mnuCancel

.Menu = .mnuMain

txtLOC.ReadOnly = True

With bsTEST

.CancelEdit()

.Position = navTest.CurrentRecord = -1

End With

.navTest.Visible = True

Case Sender Is .mnuSave

.Menu = .mnuMain

txtLOC.ReadOnly = True

With .navTest

.RecordCount += 1

.CurrentRecord = 1

End With

.navTest.Visible = True

bsTEST.EndEdit()

bsTEST.Position = 0

taTEST.Update("Locations")

End Select

End With

View 4 Replies View Related

Update Query Doesn't Insert

Mar 9, 2008

Hi, I have the following query:UPDATE lista SET audio='3847f5e9-4ef7-42d7-9e57-e5cbad9131b1.jpg' WHERE id='13';If the id already exists it'll modify the row correctly as expected. But if the id doesn't exist at the table I want the row to be inserted anyway, but this is not happening. The same query works well in mysql + php. The table has an identity increment of 1 for the primary key also. Any ideas?Thanks in advance.   

View 1 Replies View Related

SQL CE Database Doesn't Seem To Update Fast Enough.

Jan 4, 2008

I must be doing something wrong.




Code Block
TREE Form

ssql.Append("INSERT INTO FINDINGS (Facility) ")
ssql.Append("VALUES ('" & Facility & "')")
Try
Dim NewRow As Integer = dba.ExecuteSQL_Affected(ssql.ToString)
Catch ex As Exception
MsgBox("There was an error saving records.", MsgBoxStyle.Information, "No Key")
Exit Sub
End Try

Assessment.dtblFindings_Initialize()








Code Block
Public Function ExecuteSQL_Affected(ByVal sSql As String) As Integer
'//Execute the query like Insert, Update and delete
Dim RowsAffected As Integer
Try

If Conn.State = ConnectionState.Closed Then

Conn.ConnectionString = "Data Source=" & oDBConfig.LocalDBLocation & "" & oDBConfig.LocalDBName & ";"
Conn.Open()
End If
Dim cmd As New SqlCeCommand(sSql, Conn)
cmd.CommandType = CommandType.Text
RowsAffected = cmd.ExecuteNonQuery()
cmd.Dispose()
Conn.Close()
Return RowsAffected
Catch err As SqlCeException

MsgBox(Utility.ComposeSqlErrorMessage(err))
Catch ComErr As Exception

MsgBox(ComErr.ToString, MsgBoxStyle.Information)
Finally
End Try
End Function








Code Block
Assessment Form

Public Sub dtblFindings_Initialize()
Dim rdr As SqlCeDataReader
Dim dba As New DBAccess
Dim ssql As StringBuilder = New StringBuilder
ssql.Append("SELECT Facility FROM FINDINGS")
rdr = dba.OpenResultSet(ssql.ToString)
Try

rdr.Read()

While rdr.Read
...






So here is the problem. The normal function is to initiate the insert by pression a button. That should go through all the steps then hit the dtblFindings_Initialize command and rebuild the datatable. However when it happens for the first time (i.e. the first facility going into the database), the SELECT statement always returns nothing.

If I stop the application and Pull the database to the desktop, the row has been inserted. So I feel that I am somehow doing something wrong, not closing something, not initializing something....argh! Please help!!

View 1 Replies View Related

Transact SQL :: Table Doesn't Get Update Through Job

Sep 28, 2015

I have following T-SQL statement:- 

insert into [dbo].[tbl_FG_Alert_Count_All_Report] ([Date] ,[Count] ,[Rule Type])
   SELECT TOP 10 [Date]
      ,[Count]
      ,[Rule Type]
  FROM [dbo].[tbl_FG_Alert_Count_All] where Count <>'0' and DATEDIFF(dy,date,GETDATE())  = 1 order by Date desc

When I ran this T-SQL statement in SSMS; I don't get any error and as expected, I can see new data in [dbo].

[tbl_FG_Alert_Count_All_Report] table. 

Now I created one job with same T-SQL Statement. Job completes successfully with out giving any error message; But unfortunately I don't see any new data in [dbo].[tbl_FG_Alert_Count_All_Report] table.  What would be the reason that I don't see new data when job completes successfully but I can see new data after executing same T-SQL statement in SSMS?

View 3 Replies View Related

Verify If The Data Exist. If Not Insert If It Does Update

Jun 21, 2005

Im using a store proc in SQL server.I use one table to store my hockey statistics data of each player in the league.When i submit my form i would like to check if there is any sheet of that player that allready exist .. If so then i do update.. if it does not exist i do the insert statement.Here the way i figured it out ! One store proc to do the work of the insert or update. And one to check if the player exist in the statistics table. But i just cant find a way to return a good value from my second store proc. Does my logic make sence ? any ideas ?thank you<code>create procedure Hockey_Player_UpdateForwardStatistics
 @LeagueID int, @GamePlayerID int, @Games int
as
declare @PlayerID int
@PlayerID = Hockey_CheckPlayerStatistics(@LeagueID, @GamePlayerID)
if @PlayerID = 0begininsert into Hockey_PlayerStatistics( Games)values( @Games)end
ELSE
beginupdate Hockey_PlayerStatistics set Games = @Gameswhere LeagueID = @LeagueID and PlayerID = @PlayerIDend</code>

View 1 Replies View Related

Only Run Stored Procedure If Update Records Exist?

Oct 6, 2015

I am trying to put together a Stored Procedure that runs other SP's based on a records found condition. Sometimes my update table either by deleting duplicates or for other reasons is empty. Running a SP to update records on a table is not needed.

IF EXISTS (SELECT TOP 1 * FROM Work_Tables.dbo.Trace_Return_Updates WHERE TR_RecType = 'CT1')
BEGIN
EXEC IMB_Trace_Data.dbo.Update_CT1_Trace_Data
END

IF EXISTS (SELECT TOP 1 * FROM Work_Tables.dbo.Trace_Return_Updates WHERE TR_RecType = 'CT2')
BEGIN
EXEC IMB_Trace_Data.dbo.Update_CT2_Trace_Data
END

IF EXISTS (SELECT TOP 1 * FROM Work_Tables.dbo.Trace_Return_Updates WHERE TR_RecType = 'FULF')
BEGIN
EXEC IMB_Trace_Data.dbo.Update_FULF_Trace_Data
END

View 1 Replies View Related

Update If Exist-one Table To Another From Tow Date Fields- Single Row For Each Day

Apr 20, 2008

question need help
how can i use this code below not for insert
i need it for update another table but only if exist
the link to the code in this FORUM
http://forums.microsoft.com/MSDN/AddPost.aspx?PostID=3208536&SiteID=1&Quote=True






Adam Haines wrote:









GPS,



Since you have such a dependency on dates and date calculations, you should implement a calendar table. A calendar table will make calculation such as this much more simplistic.



Calendar table link http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html.

Note the calendar table I use is a little different than this one. The only thing you will need to change is isodate to dt.


Now the code to get the results you need:



Code Snippet
declare @t table(
id int,
fname char(4),
Start_Date datetime,
End_Date datetime,
val_holiday int
)
insert into @t values (111, 'aaaa', '3/15/2008', '03/21/2008', 1 )
insert into @t values (222, 'bbbb', '05/2/2008', '05/9/2008', 3)
insert into @t values (333, 'cccc', '04/3/2008', '05/15/2008', 4)
insert into @t values (333, 'cccc', '04/29/2008', '07/07/2008', 1 )

select id, fname, cal.ISODate, val_holiday
from @t t1

inner join Calendar cal
on cal.isodate >= t1.start_date and
cal.ISODate <= t1.end_date







is possible to do it
TNX

View 4 Replies View Related

Updating Sql DB. My Code Compiles, But Doesn't Update.

Sep 15, 2006

C#, Webforms, VS 2005, SQL Hi all, quick hit question.  I'm trying to update a table with an employee name and hire date.  Session variable of empID, passed from a previous page (successfully) determines which row to plop the update into. It's not working even though i compiles and makes it all the way through the code to the txtReturned.Text = "I made it" debug line...Any thoughts?    1 string szInsSql;
2
3 string sConnectionString = "Data Source=dfssql;Database=MyDB;uid=myID;pwd=myPWD";
4 SqlConnection objConn = new SqlConnection(sConnectionString);
5
6 objConn.Open();
7
8 szInsSql = "UPDATE empEmployee SET " +
9 "Name = '" + this.txtName.Text + "', " +
10 "HireDate = '" + this.txtHireDate.Text + "', " +
11 "WHERE empID = '" + Session[empID] + "'";
12
13 SqlCommand objCmd1 = new SqlCommand(szInsSql, objConn);
14 objCmd1.ExecuteNonQuery();
15
16 txtReturned.Text = "I made it";
 It's got to be a ' or a , out of place but I've looked at this code for a half hour straight, trying a variety of changes...and it still doesn't update the DB...Any help would be great.  Thank you! -Corby- 

View 3 Replies View Related

SqlDataSource Update Doesn't Work When Using Parameter

Feb 3, 2007

Hi all:
I have a list of items (actually a relation in which a user has selected an item, along with a rating for the item) in an Access database table, connected to my app with a SqlDataSource and bound to a repeater.  The repeater displays the items to the user along with a dropdown box to show the rating, and allow the user to update it.  The page connects and displays correctly.
My problem is that when the user submits the page and I iterate through the repeater items to update each rating, the updates are not being completed in the database.  The update works if I hard-code a value for the rating into the query itself, but not when using an updateparameter (pTaskRating below).  In other words if I replace pTaskRating with '5', all the correct records will be found and have their ratings updated to 5.  That means that the mySurveyId and pTaskId(DefaultValue) parameters have to be working, because the right records are found, but I can't seem to update records based on the DefaultValue of the pTaskRating parameter, even though I can verify that the DefaultValue is correct by placing a watch on it.  It seems that my problem must be in my use of that particular parameter in the query, either in properties of the parameter or in the value assigned to it.  I am extremely frustrated - any ideas would be greatly, greatly appreciated.  Thanks!
Bruck
The table I'm pulling from and updating looks like this:
SURVEY_ID (Text 50), TASK_ID (Long Int), RATING_ID (Long Int)
Here's my ASPX for the main data source:
<asp:SqlDataSource ID="sqlTaskSelections" runat="server" ConnectionString='Provider=Microsoft.Jet.OLEDB.4.0;Data Source="abc.mdb";Persist Security Info=True;Jet OLEDB:Database Password=xyz' ProviderName="System.Data.OleDb" SelectCommand="SELECT [SURVEY_ID], [TASK_ID], [RATING_ID] FROM [TBL_TASK_SELECTION] WHERE [SURVEY_ID] = mySurveyId" UpdateCommand="UPDATE [TBL_TASK_SELECTION] SET [RATING_ID] = pTaskRating WHERE ([SURVEY_ID] = mySurveyId) AND ([TASK_ID] = pTaskId)">
<UpdateParameters>

<asp:SessionParameter Name="mySurveyId" SessionField="SurveyId" DefaultValue="" /><asp:Parameter Name="pTaskId" DefaultValue="" /><asp:Parameter Name="pTaskRating" DefaultValue="" />
</UpdateParameters>
And here's the repeater (the Task ID and Rating are stored in hidden fields for easy access later):
<asp:Repeater ID="rptTaskSelections" runat="server">

<HeaderTemplate><table border="0"></HeaderTemplate>

<ItemTemplate>

<tr class="abctr"><td class="normal"><asp:DropDownList ID="cbRatings" runat="server"></asp:DropDownList><asp:HiddenField ID="hTaskId" Runat="server" Visible="false" Value='<%# Eval("TASK_ID") %>' /><asp:HiddenField ID="hRating" Runat="server" Visible="false" Value='<%# Eval("RATING_ID") %>' /> <%# Eval("TASK_ID") %></td></tr>
</ItemTemplate>

<FooterTemplate></td></tr></table></FooterTemplate>
</asp:Repeater>
And here's the page load and submit VB:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not Page.IsPostBack Then


'BIND / LOAD RATINGS TO DROPDOWN BOXES HEREDim i As IntegerDim cbCurrentRating As DropDownListDim hCurrentRating As HiddenFieldrptTaskSelections.DataSource = sqlTaskSelectionsrptTaskSelections.DataBind()


For i = 0 To rptTaskSelections.Items.Count - 1



cbCurrentRating = rptTaskSelections.Items(i).FindControl("cbRatings")hCurrentRating = rptTaskSelections.Items(i).FindControl("hRating")



cbCurrentRating.DataSource = sqlRatingscbCurrentRating.DataTextField = "RATING"cbCurrentRating.DataValueField = "ID"cbCurrentRating.DataBind()cbCurrentRating.SelectedValue = hCurrentRating.Value


Next

End If
End Sub
Protected Sub btnSubmitRateTasks_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmitRateTasks.Click

'UPDATE RATINGS HERE

Dim i As IntegerDim cbCurrentRating As DropDownListDim hCurrentTaskId As HiddenField

For i = 0 To rptTaskSelections.Items.Count - 1


cbCurrentRating = rptTaskSelections.Items(i).FindControl("cbRatings")hCurrentTaskId = rptTaskSelections.Items(i).FindControl("hTaskId")


sqlTaskSelections.UpdateParameters.Item("pTaskId").DefaultValue = hCurrentTaskId.ValuesqlTaskSelections.UpdateParameters.Item("pTaskRating").DefaultValue = cbCurrentRating.SelectedValue
sqlTaskSelections.Update()

Next

Response.Redirect("nextpage.aspx")
End Sub
 

View 3 Replies View Related

Filtered Gridview Doesn't Want To Update Records

Apr 4, 2007

I've got a listbox that displays a list of employee's names.  The employee number is the value stored in the listbox.  I then have a vaccinations gridview that displays all the vaccinations received by the selected employee in the listbox.  For some reason, when I click edit and modify a record and then click update it doesn't want to actually update the record.  It just appears to do a postback and redisplay the record without any changes.  My sqldatasource control is configured as follows: SelectCommand="SELECT * FROM [tblVaccinations] WHERE ([EmpNum] = @EmpNum)" @empnum = mylistbox.selectedvalue the update command is as follows:  UpdateCommand="UPDATE [tblVaccinations] SET [EmpNum] = @EmpNum, [VacType] = @VacType, [VacIssueDate] = @VacIssueDate, [VacExpDate] = @VacExpDate, [VacInstitution] = @VacInstitution WHERE [VaccinationNum] = @VaccinationNum"   

View 13 Replies View Related

Sysperfinfo Doesn&#39;t Update Counters Correctly. Help!!!

Mar 22, 2001

I'm using a performance monitor counter with an alert to catch merge replication conflicts. As you might have seen in my earlier psting this alert keeps running even if all conflicts have been resolved. After almost 2 days searching I found that in the table master..sysperfinfo there all the PM counters are stored still has the value 4 for conflicts/sec. When I manually create a new conflict this value becomes 5 which is nonsense since it's not the number of conflicts per second but the total number of conflicts since I started the server. If I check in PM it shows the correct value, whih of course is zero 99% of the time. Has anybody ever experienced the same kind of problem??

Or does anybody know a way of resetting the values in sysperfinfo. Even after allowing direct updates to systemtables I still can't modify the table.

Thanks in advance
Markus

View 1 Replies View Related

Update NULL Values Doesn't Work

Oct 2, 2007

Hello everybody,
I can't perform an operation apparently very easy: set a field to a NULL value.

This is the db:
Microsoft SQL Server 2000 - 8.00.760 (Intel X86)
Dec 17 2002 14:22:05
Copyright (c) 1988-2003 Microsoft Corporation
Standard Edition on Windows NT 4.0 (Build 1381: Service Pack 6)

This is the table:
CREATE TABLE [ProgettoTracce] (
[ID_Progetto] [int] NOT NULL ,
[MisDifDef] [real] NULL ,
[MisDifMeas] [real] NULL ,
[MisDifAna] [real] NULL ,
[MisDifID] [real] NULL ,
[MisDifCV] [real] NULL
) ON [PRIMARY]
GO

This is qry:
UPDATE ProgettoTracce
SET MisDifDef = NULL
WHERE ID_Progetto = 3444

The qry has been performed with no error. Then I execute SELECT * FROM ProgettoTracce WHERE ID_Progetto = 3444 and I find the value I tried to overwrite with NULL. If I update with 0 (for example) it works.
Obviously this happens on the production db, because on the development db the update with NULL works fine.
No transaction is called, db options are the same on dbs...

What's happen? Have I to call an exorcist???

Thanks in advance for any help!
Nicola

View 4 Replies View Related

Trigger (Instead Of Update) Doesn't Allow My Table Been Updated.

Mar 8, 2008

I have a Trigger Instead of Update.
When I Update my table, the trigger runs correctly but my table never is updated.


View 5 Replies View Related

SQL Server 2014 :: Update Row Always Has Results But Still Doesn't Work

Jun 11, 2014

I have this script in my database, but it always gives 2054 rows back and if I actually DO change something it doesn't even notice...

UPDATE a
SET a.[omschrijving]=SP.[omschrijving]
,a.[verkoopprijs]=SP.[verkoopprijs]
,a.[gewijzigd]=getDate()
FROM [artikelen] a
LEFT OUTER JOIN [Hofstede].[dbo].[sparepartsupdate] SP
ON a.PartNrFabrikant = sp.PartNrFabrikant
WHERE ((A.omschrijving != SP.[omschrijving]) OR (A.[verkoopprijs] != SP.[verkoopprijs]))

View 9 Replies View Related

Recordset.update With SQL Native Client Doesn't Work

Dec 4, 2006

We recently migrated from SQL Server 7 to SQL Server 2005. Now there's a curious thing with some legacy applications. I have pasted some code below. Don't judge me, because like I said, it's legacy.

You can see, that I have two connection strings. One is commented and accessing via SQL Native Client. The other one is doing this through the old SQL Server driver. Funnily enough, when I use the new Native Client driver, the exception "Run-time error '-2147467259 (80004005)' [Microsoft][SQL Native Client]Invalid attribute value" is thrown in the rsPorder2.Update line. With the old driver, this works just alright.

Is this a bug? Is there a way, to make the code run, because we don't want to search the whole application for other occurances, if not necessary.

Any insights would be greatly appreciated.

Best regards,
DD

Dim ilinx As New ADODB.Connection
Dim rsPorder As New ADODB.Recordset
Dim rsPorder2 As New ADODB.Recordset
Dim cmdLinx As New ADODB.Command
Dim strConn As String

Dim lvIli_number As String

'strConn = "DRIVER=SQL Native Client;Server=10.0.14.7;Description=Test2k;UID=sa;PWD=asdf;APP=Microsoft® Access;WSID=DEHHC023;DATABASE=Linx;Network=DBMSSOCN;"

strConn = "DRIVER=SQL Server;Server=10.0.14.7;Description=Test2k;UID=sa;PWD=asdf;APP=Microsoft® Access;WSID=DEHHC023;DATABASE=Linx;Network=DBMSSOCN;"
ilinx.Open strConn
Set cmdLinx.ActiveConnection = ilinx

lvIli_number = "12345"
cmdLinx.CommandText = "SELECT * FROM porder WHERE previous_ili_no = '" & lvIli_number & "' "
cmdLinx.CommandType = 1

rsPorder.Open cmdLinx, , 1, 1

If rsPorder.EOF Then

cmdLinx.CommandText = "SELECT * FROM porder WHERE ili_no = '" & lvIli_number & "' "
cmdLinx.CommandType = 1
rsPorder2.Open cmdLinx, , 1, 3

If rsPorder2.RecordCount > 0 Then

rsPorder2("Locked") = 0
rsPorder2.Update
End If

End If
rsPorder.Close

View 7 Replies View Related

SQL Server 2008 :: SSIS To Import And Update Data If Exist On The Destination?

May 25, 2015

I am working on SSIS wehre I need to work on a flat file as a source and needed to import it to database. If the destination table have the record already, I need to update it and if not exist, I just need to import the whole data.

View 9 Replies View Related

Transact SQL :: Multiple Update Top On Commit Transaction Doesn't Work

Jul 10, 2015

I have this sql stored procedure in SQL Server 2012:

ALTER PROCEDURE [dbo].[CreateBatchAndSaveExternalCodes]
@newBatches as dbo.CreateBatchList READONLY
, @productId int
, @cLevelRatio int
, @nLevelRatio int
AS
set nocount on;

[Code] ....

View 4 Replies View Related

Grant Execute On Sproc Doesn't Grant Privilege To Update?

Oct 31, 2014

I am writing a stored procedure which updates a table, but when I run the stored procedure using a login that I have granted execute privileges on, then I get a message that I cannot run an update on the table. This would happen in dynamic sql... while my SQL has parameter references, I don't think it is considered dynamic SQL?

sproc:
CREATE PROCEDURE [schemaname].[SetUserCulture]
@UserID int
, @Culture nvarchar(10)
AS
UPDATE dbo.SecUser
SET Culture = @Culture
WHERE UserID = @UserID

execute SQL:
EXEC schemaname.SetUserCulture @UserID = 9, @Culture = N'x'

error:
The UPDATE permission was denied on the object 'SecUser', database 'DatabaseName', schema 'schemaname'.

View 8 Replies View Related

Update Query In Ms-access Doesn't Workin C#, But Does Work In Ms-access

Apr 18, 2007

Hi,

I have an application that uses following code:



Code Snippet







using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Collections;

namespace TimeTracking.DB
{
public class sql
{
OleDbConnection conn;

//
//the constructor for this class, set the connectionstring
//
public sql()
{
DBConnectionstring ConnectToDB = new DBConnectionstring();
conn = ConnectToDB.MyConnection();
}

//
//
//
public void UpdateEntry(int ID, string Week, string Year, string Date, string Project, string Action, string Time, string Comment)
{
int m_ID = ID;
int m_Week = (Convert.ToInt32(Week));
int m_Year = (Convert.ToInt32(Year));
string m_Date = Date;
string m_Project = Project;
int m_ProjectID = new int();
string m_Action = Action;
int m_ActionID = new int();
Single m_Time = (Convert.ToSingle(Time));
string m_Comment = Comment;

//
//get the project ID from the database and store it in m_ProjectID
//
OleDbCommand SelectProjectID = new OleDbCommand("SELECT tblProject.ProjectID FROM tblProject"
+ " WHERE (((tblProject.Project) LIKE @Project))", conn);

SelectProjectID.Parameters.AddWithValue("@Project", m_Project);

try
{
//open the connection
conn.Open();

OleDbDataReader Dataset = SelectProjectID.ExecuteReader();

while (Dataset.Read())
{
m_ProjectID = (int)Dataset["ProjectID"];
}

Dataset.Close();
}

//Some usual exception handling
catch (OleDbException e)
{
throw (e);
}

//
//get the action ID from the database and store it in m_ActionID
//
OleDbCommand SelectActionID = new OleDbCommand("SELECT tblAction.ActionID FROM tblAction"
+ " WHERE (((tblAction.Action) LIKE @Action))", conn);

SelectActionID.Parameters.AddWithValue("@Action", m_Action);

try
{
OleDbDataReader Dataset = SelectActionID.ExecuteReader();

while (Dataset.Read())
{
m_ActionID = (int)Dataset["ActionID"];
}

Dataset.Close();
}

//Some usual exception handling
catch (OleDbException e)
{
throw (e);
}



//
//
//
OleDbCommand Query = new OleDbCommand("UPDATE [tblEntry] SET [tblEntry].[Weeknumber] = @Week,"
+ " [tblEntry].[Year] = @Year, [tblEntry].[Date] = @Date, [tblEntry].[Project] = @ProjectID, [tblEntry].[Action] = @ActionID,"
+ " [tblEntry].[Hours Spent] = @Time, [tblEntry].[Comments] = @Comment WHERE (([tblEntry].[ID]) = @ID)", conn);

Query.Parameters.AddWithValue("@ID", m_ID);
Query.Parameters.AddWithValue("@Week", m_Week);
Query.Parameters.AddWithValue("@Year", m_Year);
Query.Parameters.AddWithValue("@Date", m_Date);
Query.Parameters.AddWithValue("@ProjectID", m_ProjectID);
Query.Parameters.AddWithValue("@ActionID", m_ActionID);
Query.Parameters.AddWithValue("@Time", m_Time);
Query.Parameters.AddWithValue("@Comment", m_Comment);

try
{
Query.ExecuteNonQuery();
}

//Some usual exception handling
catch (OleDbException e)
{
throw (e);
}

finally
{
//close the connection
if (conn != null)
{
conn.Close();
}
}
}
}
}

Code Snippet



The update statement is not working in my application, no error in C# and no error in ms-access. When I paste the update query into the ms-access query tool and replace the parameter values (@....) with real values, is will update the record.

What am I overseeing here?
--Pascal

View 13 Replies View Related

Table Doesn&#39;t Exist

Aug 29, 2001

hi i am running this program
and its giving some problem while execution.
When the program tries to create the table expt1..its says
Msg 2714, Level 16, State 1
There is already an object named 'expt1' in the database.

and if i try to drop the table expt1 it says
Msg 3701, Level 11, State 1
Cannot drop the table 'expt1', because it doesn't exist in the system catalogs.

How should I resolve this problem...?
==========================



Declare @cmdstring varchar(255)
Declare @filename varchar(32)
DECLARE @v datetime

SELECT @v = GetDate()
Create table expt1(GMSKEY char,CONTRACT char,ORIGINALCONTRACT char,STATEMENTID char,
STATEMENTDATE char ,partner char ,ADDRESSSEQ char,BOOKINGAMOUNT char,
BOOKINGCURRENCY char,TAXEDIND char,TAXTYPE char,
DUEPERIOD char,ACCOUNTNUMBER char,PRODMONTH char,PRODYEAR char,BOOKINGUNIT char,
BOOKINGQUANTITY char,STATEMENTSEQ char,COSTID char,DELIVERYMETHOD char)

SELECT
DETAILTRANS.GMSKEY,
DETAILTRANS.CONTRACT,
DETAILTRANS.ORIGINALCONTRACT,
DETAILTRANS.STATEMENTID,
convert(varchar,DETAILTRANS.STATEMENTDATE,106) statementdate,
DETAILTRANS.partner,
DETAILTRANS.ADDRESSSEQ,
DETAILTRANS.BOOKINGAMOUNT,
DETAILTRANS.BOOKINGCURRENCY,
DETAILTRANS.TAXEDIND,
DETAILTRANS.TAXTYPE,
TITLECT.DUEPERIOD,
DETAILTRANS.ACCOUNTNUMBER,
DETAILTRANS.PRODMONTH,
DETAILTRANS.PRODYEAR,
DETAILTRANS.BOOKINGUNIT,
DETAILTRANS.BOOKINGQUANTITY,
DETAILTRANS.STATEMENTSEQ,
DETAILTRANS.COSTID,
TITLECT.DELIVERYMETHOD,

'' RECEND
INTO expt1
FROM DETAILTRANS,TITLECT

where DETAILTRANS.TITLEID=TITLECT.TITLEID

AND DETAILTRANS.CONTRACT IS NOT NULL
AND DETAILTRANS.CONTRACT!='N/A'
AND DETAILTRANS.EXPREV='E'
AND DETAILTRANS.PRELIMORFINAL='F'
AND DETAILTRANS.postedDATE IS NULL
ORDER BY DETAILTRANS.GMSKEy


select @filename = 'XAPIALTMKT'+CONVERT(varchar, @v, 112)+ SUBSTRING(CONVERT(varchar, @v, 108), 1, 2)
+ SUBSTRING(CONVERT(varchar, @v, 108), 4, 2)+ SUBSTRING(CONVERT(varchar, @v, 108), 7, 2) + '.TXT'

Select @cmdstring = 'bcp GM_PROD..expt1 out d:est' + @filename + ' -c -t"|" -r -S -Usa -Psa'

exec master..xp_cmdshell @cmdstring
drop table expt1
===========
Thanks
Harish

View 1 Replies View Related

Message_Type Doesn't Exist

Dec 10, 2007

I have a simple question I hope someone can verify for me. At my company we are sending 2 different response messages. One is a commit response and one is a finalize response. Currently the service that we are sending the responses to only cares about the commit but later on in development they will care about the finalize response. The service that we are sending the finalize message to simply does not have a finalize message type and if running the profiler on it an error occurs: "This message could not be delivered because the message type name could not be found." And the message is lost. This doesn't really matter to anyone because at the time no one cares about the message. But I want to make sure that that is expected. After all service broker is supposed to be reliable. So my question is: If a message_type doesn't exist on the target side, will the message disappear and is that normal service broker behavior. I would hate to one day find the transmission queue with thousands of messages in it.

View 5 Replies View Related

SQL Doesn't Exist Or Access Denied.

Dec 18, 2006

 Hi, I not sure where my connection string is incorrect. I cant' access the SQL Server through Query Analyzer but the program can't. here is my connection string."ConnectionString" value="Data Source=xx.xx.xx.xx;Initial Catalog=xxx;UID=xxx;PWD=xxx;MAX POOL SIZE=5">
In the Query analyzer, i choose the SQL Server Authentication and provide login and password. I can access the database. Also, i can access the database at local computer. But, i can't access the database by other pc throught network.
 do i need to provide any other in the connection string?
 
regards,

View 9 Replies View Related

Catch Sql Command If Value Doesn't Exist

Jul 31, 2007

 I have a sql command that is loaded on page load that collects information based on the query string. The query string is a random group of numbers and letters. How do I catch it and direct to an error page if the query can not be found in the database?
 Thanks!

View 5 Replies View Related

How Do You Exclude Data That Doesn't Exist?

Apr 1, 2005

I have a cube that is showing measures that don't exist. Let me give an example. This example will include 3 dimensions, product, location, and time. The fact table measure will be sales.

Here are the distinct values if you were to write a sql query against the dimensionl model that feeds the cube.

Product Location Time Sales
A X 1/04 200
B Y 1/04 100

A X 2/04 300

In the cube, if you were to look at product by location for just 2/04, you would see:

Product Location Sales
All Loc 300
A X 300
Y

All Loc
B X
Y

How do you get rid of the zero's or combinations that don't exist?

Thanks,

Doug

View 1 Replies View Related

Table Or View Doesn't Exist

Jun 22, 2006

Hello I am trying to run a select statement in Java against SQL Server 2K. But I keep getting an error saying that the table doesn't exist.

Is this a problem with my SQL statement?

select * from counting

I also tried

select * from dbo.counting

my connection url is

jdbc:microsoft:sqlserver://IS-0081526:1433;databaseName=bail;



I can run these queries from Query analyzer I am able to run them with the same account and login.

View 4 Replies View Related

Update On Machine Runs Immediately, Update On Linked Server Takes 8 Minutes

Jan 2, 2008

What's up with this?

This takes like 0 secs to complete:

update xxx_TableName_xxx
set d_50 = 'DE',modify_timestamp = getdate(),modified_by = 1159

where enc_id in

('C24E6640-D2CC-45C6-8C74-74F6466FA262',

'762E6B26-AE4A-4FDB-A6FB-77B4782566C3',

'D7FBD152-F7AE-449C-A875-C85B5F6BB462')

but From linked server this takes 8 minutes????!!!??!:

update [xxx_servername_xxxx].xxx_DatabaseName_xxx.dbo.xxx_TableName_xxx
set d_50 = 'DE',modify_timestamp = getdate(),modified_by = 1159

where enc_id in

('C24E6640-D2CC-45C6-8C74-74F6466FA262',

'762E6B26-AE4A-4FDB-A6FB-77B4782566C3',

'D7FBD152-F7AE-449C-A875-C85B5F6BB462')


What settings or whatever would cause this to take so much longer from the linked server?

Edit:
Note) Other queries from the linked server do not have this behavior. From the stored procedure where we have examined how long each query/update takes... this particular query is the culprit for the time eating. I thought it was to do specefically with this table. However as stated when a query window is opened directly onto that server the update takes no time at all.

2nd Edit:
Could it be to do with this linked server setting?
Collation Compatible
right now it is set to false? I also asked this question in a message below, but figured I should put it up here.

View 5 Replies View Related

SQL Server 2000 - Issue W/ UPDATE - Single Row Update Returns 2 Different Messages

Nov 11, 2007

I am hoping someone can shed light on this odd behavior I am seeing running a simple UPDATE statement on a table in SQL Server 2000.  I have 2 tables - call them Table1 and Table2 for now (among many) that need to have certain columns updated as part of a single transaction process.   Each of the tables has many columns. I have purposely limited the target column for updating to only ONE of the columns in trying to isolate the issue.  In one case the UPDATE runs fine against Table1... at runtime in code and as a manual query when run in QueryAnalyzer or in the Query window of SSManagementStudio - either way it works fine. 
However, when I run the UPDATE statement against Table2 - at runtime I get rowsaffected = 0 which of course forces the code to throw an Exception (logically).  When I take out the SQL stmt and run it manually in Query Analyzer, it runs BUT this is the output seen in the results pane...
(0 row(s) affected)
(1 row(s) affected)
How does on get 2 answers for one query like this...I have never seen such behavior and it is a real frustration ... makes no sense.  There is only ONE row in the table that contains the key field passed in and it is the same key field value on the other table Table1 where the SQL returns only ONE message (the one you expect)
(1 row(s) affected)
If anyone has any ideas where to look next, I'd appreciate it.
Thanks 
 

View 2 Replies View Related

How To Correctly Update A Table Which Values Can Be Either Inserted/updated/deleted On Update?

Feb 16, 2006

Hi SQL fans,I realized that I often encounter the same situation in a relationdatabase context, where I really don't know what to do. Here is anexample, where I have 2 tables as follow:__________________________________________ | PortfolioTitle|| Portfolio |+----------------------------------------++-----------------------------+ | tfolio_id (int)|| folio_id (int) |<<-PK----FK--| tfolio_idfolio (int)|| folio_name (varchar) | | tfolio_idtitle (int)|--FK----PK->>[ Titles]+-----------------------------+ | tfolio_weight(decimal(6,5)) |+-----------------------------------------+Note that I also have a "Titles" tables (hence the tfolio_idtitlelink).My problem is : When I update a portfolio, I must update all theassociated titles in it. That means that titles can be either removedfrom the portfolio (a folio does not support the title anymore), addedto it (a new title is supported by the folio) or simply updated (atitle stays in the portfolio, but has its weight changed)For example, if the portfolio #2 would contain :[ PortfolioTitle ]id | idFolio | idTitre | poids1 2 1 102 2 2 203 2 3 30and I must update the PortfolioTitle based on these values :idFolio | idTitre | poids2 2 202 3 352 4 40then I should1 ) remove the title #1 from the folio by deleting its entry in thePortfolioTitle table2 ) update the title #2 (weight from 30 to 35)3 ) add the title #4 to the folioFor now, the only way I've found to do this is delete all the entriesof the related folio (e.g.: DELETE TitrePortefeuille WHERE idFolio =2), and then insert new values for each entry based on the new givenvalues.Is there a way to better manage this by detecting which value has to beinserted/updated/deleted?And this applies to many situation :(If you need other examples, I can give you.thanks a lot!ibiza

View 8 Replies View Related

ASP Update Method Not Working After A MSDE To MSSQL 2005 Expess Update

Oct 20, 2006

The Folowing code is not working anymore. (500 error)

Set objRS = strSQL1.Execute
strSQL1 = "SELECT * FROM BannerRotor where BannerID=" & cstr(BannerID)
objRS.Open strSQL1, objConn , 2 , 3 , adCmdText
If not (objRS.BOF and objRS.EOF) Then
objRS.Fields("Exposures").Value =objRS.Fields("Exposures").Value + 1
objRS.update
End If
objRS.Close

The .execute Method works fine

strSQL1 = "UPDATE BannerRotor SET Exposures=Exposures+1 WHERE BannerID=" & cstr(BannerID)
objConn.Execute strSQL1

W2003 + IIS6.0

Pls advice?

View 1 Replies View Related

SQL Server 2008 :: Update Null Enabled Field Without Interfering With Rest Of INSERT / UPDATE

Apr 16, 2015

If I have a table with 1 or more Nullable fields and I want to make sure that when an INSERT or UPDATE occurs and one or more of these fields are left to NULL either explicitly or implicitly is there I can set these to non-null values without interfering with the INSERT or UPDATE in as far as the other fields in the table?

EXAMPLE:

CREATE TABLE dbo.MYTABLE(
ID NUMERIC(18,0) IDENTITY(1,1) NOT NULL,
FirstName VARCHAR(50) NULL,
LastName VARCHAR(50) NULL,

[Code] ....

If an INSERT looks like any of the following what can I do to change the NULL being assigned to DateAdded to a real date, preferable the value of GetDate() at the time of the insert? I've heard of INSTEAD of Triggers but I'm not trying tto over rise the entire INSERT or update just the on (maybe 2) fields that are being left as null or explicitly set to null. The same would apply for any UPDATE where DateModified is not specified or explicitly set to NULL. I would want to change it so that DateModified is not null on any UPDATE.

INSERT INTO dbo.MYTABLE( FirstName, LastName, DateAdded)
VALUES('John','Smith',NULL)

INSERT INTO dbo.MYTABLE( FirstName, LastName)
VALUES('John','Smith')

INSERT INTO dbo.MYTABLE( FirstName, LastName, DateAdded)
SELECT FirstName, LastName, NULL
FROM MYOTHERTABLE

View 9 Replies View Related







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