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


ADVERTISEMENT

JDBC: PreparedStatement#getParameterMetaData() Doesn't Work For INSERT SQL Query

Feb 26, 2008

Hi,

I'm using MSSQL 2005 JDBC driver version 1.2 with MSSQL Server 2005. Getting parameter's metadata doesn't seem to be working properly there. PreparedStatement#getParameterMetaData() works fine if PreparedStatement is created for some SELECT but fails for any INSERT statements. The same code works fine with other DBs (I checked with HSQLdb and PostgreSQL). See sample below

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbcqlserver://mssql2005\mssql2005;DatabaseName=alexdtms;user=xxx;password=xxx";

// I don't care about non-closed statements, it's just sample code
Connection con = DriverManager.getConnection(connectionUrl);
con.createStatement().executeUpdate("CREATE Table Table1 (RECORD_ID varchar, TgtQty float)");
PreparedStatement ps = con.prepareStatement("INSERT INTO Table1 VALUES ( ?,? )");

ParameterMetaData pmd = ps.getParameterMetaData();// <-- !!!! Exception is thrown here
for (int i = 1, count = pmd.getParameterCount(); i <= count; i++)
{
System.err.println(">>>>AD_TEMP " + pmd.getParameterType(i) + " " + pmd.getParameterTypeName(i) + " " + pmd.getParameterMode(i));
}

Thanks,
Alexander Dolgin

View 1 Replies View Related

Can I Roll Back Certain Query(insert/update) Execution In One Page If Query (insert/update) In Other Page Execution Fails In Asp.net

Mar 1, 2007

Can I roll back certain query(insert/update) execution in one page if  query (insert/update) in other page  execution fails in asp.net.( I am using sqlserver 2000 as back end)
 scenario
In a webpage1, I have insert query  into master table and Page2 I have insert query to store data in sub table.
 I need to rollback the insert command execution for sub table ,if insert command to master table in web page1 is failed. (Query in webpage2 executes first, then only the query in webpage1) Can I use System. Transaction to solve this? Thanks in advance

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

Need Query For Update And Insert In One Go.

Jun 13, 2006

Hi All,
Please look at the following tables. I have Two tables
Data and TmpData with the following structure.

Data ( All int columns, ID column is Primary and identity)

Id UserID PrgID RoldID
322112
323122
324132
325212
326222
327232
328312
329322
330332


TmpData
Id UserID PrgID RoldID
82113
83123
84133
85213
86223
87233
912012
922022
932032
942112
952122
962132


Now I need to run a query so that
Part 1: It updates existing RoleId columns ( Based on Userid,PrgID) in 'Data' Table with corresponding values from 'Data' table.
Part2 : It inserts new rows in 'TmpData' to 'Data' table.

I am done with Part1 using the simple update statement.

Update Data
Set Data.programroleid=tmp.ProgramRoleID
from TmpData tmp
where Data.userid=tmp.UserId
and Data.programId=tmp.ProgramId

This works fine for existing userids,programids in 'Data' and 'TmpData' tables. But I am struggling with inserting new rows into Data from 'TmpData' ( That exists only in 'tmpData' table). Based on above table structures how do I insert new data into 'Data' table from 'TmpData'.

View 2 Replies View Related

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

Automatically Trigger A Sum From One Table To Another Upon Update/insert Query

Jul 12, 2005

I'm trying to update (increment)
Company.SumtotalLogons
from CompanyUsers.NumberOfLogons
where CompanyUsers.CompanyID = Company.CompanyID

I'd like to either write a formula (if it is even possible to fire a formula from one table update/insert to increment a field in another table), or a stored procedure that triggers an auto update/append into Company.SumTotalLogons

I know this is possible in access, so i'm wondering how to go about it in ms-sql?

any ideas?

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

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

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

Simple Insert From Querystring Doesn't Work - Why?

Apr 13, 2006

I want to insert values from the querystring but nothing happens with this code (the sp works great from the Query Analyzer):
 
<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"InsertCommand="spSearch_row_insert" InsertCommandType="StoredProcedure">
<InsertParameters>
<asp:QueryStringParameter Name="CustomerID" QueryStringField="1" DefaultValue="1" Type="String" />
<asp:QueryStringParameter Name="SearchID" QueryStringField="2" DefaultValue="1" Type="String"/>
<asp:QueryStringParameter Name="SearchDate" QueryStringField="3" DefaultValue="1" Type="String" />
<asp:QueryStringParameter Name="IP" QueryStringField="4" DefaultValue="1" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
</form>
 
I'm very grateful for help!// G

View 3 Replies View Related

DB Engine :: Bulk Insert Doesn't Load

Jul 31, 2015

I have a Bulk insert that doesn't load but doesn't error,

SET @SQL= 'BULK INSERT dbo.LexisNexis_import_BANKRUPTCY FROM ''' + @ImportFile + ''' WITH (FIRSTROW = 2, FORMATFILE = ''' + @FormatFilePath + ''' )'
EXEC(@SQL)

All columns in the csv are double quoted so I stip them out in a format file.There is data in the source file. Why this Isn't working?

View 4 Replies View Related

Prepared Statement Doesn't Insert String

Jul 30, 2007

Hi,

I am facing a problem while using pepared statement for inserting data in MS-Access db.








Code Snippet

private const String CONN_STR = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\TestDb.mdb";
conDatabase.Open(CONN_STR, "", "", -1);
String sQuery = "INSERT INTO " + sTableName +
" ([FileName],[IsCopied],[Size]) VALUES (@FileName,@IsCopied,@Size)";
cmdPrepStmnt.ActiveConnection = conDatabase;
cmdPrepStmnt.CommandText = sQuery;
cmdPrepStmnt.CommandType = CommandTypeEnum.adCmdText;
cmdPrepStmnt.Prepared = true;
int iCount = 0;
foreach (FileInfo f in fInfo)
{
Console.WriteLine("Adding File " + ++iCount + " of " + fInfo.Length + "; " + f.Name);
Parameter p1 = cmdPrepStmnt.CreateParameter("@FileName", ADODB.DataTypeEnum.adVarWChar, ParameterDirectionEnum.adParamInput, 255, f.FullName);
Parameter p3 = cmdPrepStmnt.CreateParameter("@IsCopied", ADODB.DataTypeEnum.adBoolean, ParameterDirectionEnum.adParamInput, 10, false);
Parameter p5 = cmdPrepStmnt.CreateParameter("@Size", ADODB.DataTypeEnum.adInteger, ParameterDirectionEnum.adParamInput, 10, f.Length);
cmdPrepStmnt.Parameters.Append(p1);
cmdPrepStmnt.Parameters.Append(p3);
cmdPrepStmnt.Parameters.Append(p5);
cmdPrepStmnt.Execute(out objAffected, ref obj, 0);

}


Code Snippet





FileName is coming as blank in db, while in debug mode i can see that it is being set with a proper filename. The other 2 params are inserting fine.

The FileName field is set as Text field with width length 255, and the incoming data is always shorter than 255 chars. The insertion happens without any errors/exceptions. I have also tried replacing the data for filename with a string like "Test", still it is inserting blank string.

Please help.

View 3 Replies View Related

Enable Identity Insert Doesn't Work

Jan 4, 2008

Hi,

I'm trying to transfer data between two 2005 databases using the import/export method. I set the Enable Identity insert to true - edit mappings option - on all the tables but I still get the ID set back to 1. I want to add some live data to an altered database structure, and I'm assuming the import/export tool is the way to do this.

I'm using sql server management studio, SP1

Thanks, this is becoming really frustrating.

Peter Cat

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

Why The Query Works In Query Analyser And Doesn't Work In Reporting Service ?

Apr 30, 2007



Hello everybody,



I'm developing a report using the following structure :



declare @sql as nvarchar(4000)

declare @where as nvarchar(2000)



set @sql = 'select ....'



If <conditional1>

begin

set @where = 'some where'

end



If <conditional2>

begin

set @where = 'some where'

end



set @sql = @sql + @where



exec(@sql)



I run it in query analyser and works fine, but when I try to run in Reporting Services, Visual studio stops responding and the cpu reaches 100 %.



I realize that when I cut off the if clauses, then it works at Reporting services.

Does anybody know what is happening?

Why the query works in query analyser and doesn't work in Reporting Service ?



Thanks,



Maurício

View 2 Replies View Related

Simple Lab For Insert/retrive BLOB Doesn't Work, Why Not?

Sep 17, 2007



This is simple enough and I'm stumped. Why doesn't this work?




Code Snippet
use w
go
-- Create image warehouse
create table dbo.ImageWarehouse (
[ImageWarehouseID] int identity(1,1) primary key,
[ImageName] varchar(100),
Photo varbinary(max))
Go
-- Import image
Insert into dbo.ImageWarehouse
([ImageName]) values ('testingimage.gif')
update dbo.ImageWarehouse
set Photo =
(SELECT * FROM OPENROWSET(BULK 'c: estingimage.gif', SINGLE_BLOB)AS x )
WHERE [ImageName]='testingimage.jpg'
go
-- Check population
--delete from dbo.ImageWarehouse
select * from dbo.ImageWarehouse
go
-- Export image
declare @SQLcommand nvarchar(4000)
set @SQLcommand = 'bcp "SELECT top 1 Photo FROM w.dbo.ImageWarehouse WHERE ImageName = ''testingimage.gif''" queryout "c: estingimage_out.gif" -T -N -S [my server name]'
exec xp_cmdshell @SQLcommand
go





I successfully see




Code SnippetImageWarehouseID ImageName Photo
1 testingimage.gif 0x4749463839615802C (long hex string)



then




Code Snippet
output
NULL
Starting copy...
NULL
1 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.): total 1
NULL






But testingimage_out.gif is unreadable. It's the same size (28k) as the original trestingimage.gif. Same result with a .jpg file. Try to open the file and it's just red X.

No SQL errors. Just result error. What am I overlooking?




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

Query Call By App Runs Long, Same Query In QA Doesn't.

Feb 19, 2008

Hi Guys,

I've got a stored proc used for order generation which runs long sometimes when called from within our app. A normal run will complete within 20s, a long run will get terminated by the app at the 6 minute mark.

When it runs long once, repeated attempts will also do so until I execute the same query the app did, but from within Query Analyzer. At which time the problem will disappear for a day or two. The app connects to the SQL Server 200 SP4 database using ADO.

I suspected statistics might be at fault here but have tried both "UPDATE STATISTICS table WITH FULLSCAN" and "DBCC DBREINDEX('table') to no avail. This issue has occurred and been worked around in this manner a few dozen times.

Any idea what might be going on here?

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

Can I Insert/Update Large Text Field To Database Without Bulk Insert?

Nov 14, 2007

I have a web form with a text field that needs to take in as much as the user decides to type and insert it into an nvarchar(max) field in the database behind.  I've tried using the new .write() method in my update statement, but it cuts off the text after a while.  Is there a way to insert/update in SQL 2005 this without resorting to Bulk Insert? It bloats the transaction log and turning the logging off requires a call to sp_dboptions (or a straight-up ALTER DATABASE), which I'd like to avoid if I can.

View 6 Replies View Related

T-SQL (SS2K8) :: Insert / Update Triggers When Insert Run Via Script

Oct 23, 2014

I'm working on inserting data into a table in a database. The table has two separate triggers, one for insert and one for update (I don't like it this way, but that's how it's been for years). When there is a normal insert, done via a program, it looks like the triggers work fine. When I run an insert manually via a script, the first insert trigger will run, but the update trigger will fail. I narrowed down the issue to a root cause.

This root issue is due to both triggers using the same temporary table name. When the second trigger runs, there's an error stating that a few columns don't exist. I went to my test server and test db and changed the update trigger so that the temporary table is different than the insert trigger temporary table, the triggers work fine. The weird thing is that if the temporary table already exists, when the second trigger tries to create the temporary table, I would expect it to fail and say that it already exists.I'm probably just going to update the trigger tonight and change the temporary table name.

View 1 Replies View Related

DTS SQL Query Doesn&#39;t Run

Aug 27, 2001

I'm pulling data from Oracle 8.05 using Oracle ODBC with DTS to SQL Server 7 sr2. If I choose my columns only, I have no problem. When I try to edit the SQL statement either in the Import Wizard or the DTS Designer, the package won't run. I am selecting on a date column. I corrected the TSQL using the "convert" statement. Does someone know what might be happening?

View 1 Replies View Related

Why Doesn't This Query Run??

May 3, 2008



Hi can any one see why this will now run when sent to the server. Don't worry about the parameters as these are replaced at runtime in a c# app I have created.

It is not the easiest to read but your help is appreciated.




Code Snippet
/* Create new table of dates using the Week Ending date selected by the user
This is a list of week ending dates between the start and end dates selected by the user */
DECLARE @Temp AS DATETIME
DECLARE @result table(WeekEndDate datetime)
SET @Temp = @Start + ((@WeekEnding - (DATEPART(w, @Start) - 1)) % 7) + CASE WHEN (@WeekEnding - (DATEPART(w, @Start) - 1))
< 0 THEN 7 ELSE 0 END

WHILE @Temp <= @End
BEGIN
INSERT INTO @result values(@Temp)
SET @Temp = @Temp + 7
END

/* Aggregate data by Week ending date so that we can see the Metrics for that particular week*/
SELECT dbo.MSP_WEB_PROJECTS.PROJ_NAME AS Project, EV_View.[Week Ending], EV_View.BAC, EV_View.EV, EV_View.PV,
EV_View.AC, EV_View.FV, EV_View.FC, EV_View.[Baseline Work], EV_View.[Work], EV_View.[Actual Work], EV_View.[ETC],
CASE WHEN EV_View.[Week Ending] BETWEEN dbo.MSP_VIEW_PROJ_PROJECTS_STD.ProjectStartDate AND
dbo.MSP_VIEW_PROJ_PROJECTS_STD.ProjectFinishDate THEN 'YES' ELSE 'NO' END AS [1 Project Duration]
FROM
(
SELECT ProjectID, WeekEndDate AS [Week Ending], SUM(BAC) / @TimeUnits AS BAC, SUM(EV) / @TimeUnits AS EV,
SUM(PV) / @TimeUnits AS PV, SUM(AC) / @TimeUnits AS AC, SUM(FV) / @TimeUnits AS FV, SUM(FC) / @TimeUnits AS FC,
SUM([Baseline Work]) / @TimeUnits AS [Baseline Work], SUM([Work]) / @TimeUnits AS [Work],
SUM([Actual Work]) / @TimeUnits AS [Actual Work], (SUM([Work]) - SUM([Actual Work])) / @TimeUnits AS ETC
FROM
(
SELECT ProjectID, WeekEnds.WeekEndDate, BAC,
CASE WHEN derivedtbl_1.[Baseline Finish] BETWEEN WeekEnds.WeekEndDate - 6 AND WeekEnds.WeekEndDate THEN derivedtbl_1.PV END AS PV,
CASE WHEN derivedtbl_1.[Actual Finish] BETWEEN WeekEnds.WeekEndDate - 6 AND WeekEnds.WeekEndDate THEN derivedtbl_1.EV END AS EV,
CASE WHEN derivedtbl_1.[Actual Finish] BETWEEN WeekEnds.WeekEndDate - 6 AND WeekEnds.WeekEndDate THEN derivedtbl_1.AC END AS AC,
CASE WHEN (derivedtbl_1.Finish BETWEEN WeekEnds.WeekEndDate - 6 AND WeekEnds.WeekEndDate) THEN derivedtbl_1.[Baseline Work] END AS FV,
CASE WHEN (derivedtbl_1.Finish BETWEEN WeekEnds.WeekEndDate - 6 AND WeekEnds.WeekEndDate) THEN derivedtbl_1.[Estimate at Complete] END AS FC,
CASE WHEN (TP.AssignmentTimeStart BETWEEN WeekEnds.WeekEndDate - 6 AND WeekEnds.WeekEndDate) THEN TP.[Baseline Work] END AS [Baseline Work],
CASE WHEN (TP.AssignmentTimeStart BETWEEN WeekEnds.WeekEndDate - 6 AND WeekEnds.WeekEndDate) THEN TP.[Work] END AS [Work],
CASE WHEN (TP.AssignmentTimeStart BETWEEN WeekEnds.WeekEndDate - 6 AND WeekEnds.WeekEndDate) THEN TP.[Actual Work] END AS [Actual Work]
FROM
(
SELECT dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.WPROJ_ID, dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.AssignmentTimeStart,
SUM(ISNULL(dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.AssignmentTimeBaselineWork, 0)) AS [Baseline Work],
SUM(ISNULL(dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.AssignmentTimeWork, 0)) AS [Work],
SUM(ISNULL(dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.AssignmentTimeActualWork, 0)) AS [Actual Work],
SUM(ISNULL(dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.AssignmentTimeActualWorkProtected, 0)) AS [Actual Work Protected]
FROM dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY INNER JOIN
dbo.MSP_VIEW_PROJ_ASSN_STD ON
dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.WPROJ_ID = dbo.MSP_VIEW_PROJ_ASSN_STD.WPROJ_ID AND
dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.AssignmentUniqueID = dbo.MSP_VIEW_PROJ_ASSN_STD.AssignmentUniqueID
WHERE (dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.AssignmentTimeStart <= @End) AND
(dbo.MSP_VIEW_PROJ_ASSN_TP_BY_DAY.AssignmentTimeStart >= @Start)
)
AS TP INNER JOIN
(
SELECT dbo.MSP_WEB_PROJECTS.WPROJ_ID AS ProjectID,
dbo.MSP_WEB_PROJECTS.PROJ_NAME AS Project, dbo.MSP_VIEW_PROJ_TASKS_STD.TaskName AS [Task Name],
DATEADD(day, 0, DATEDIFF(day, 0, dbo.MSP_VIEW_PROJ_TASKS_STD.TaskBaselineStart)) AS [Baseline Start],
DATEADD(day, 0, DATEDIFF(day, 0, dbo.MSP_VIEW_PROJ_TASKS_STD.TaskBaselineFinish)) AS [Baseline Finish],
DATEADD(day, 0, DATEDIFF(day, 0, dbo.MSP_VIEW_PROJ_TASKS_STD.TaskActualFinish)) AS [Actual Finish],
dbo.MSP_VIEW_PROJ_TASKS_STD.TaskBaselineWork AS [Baseline Work],
dbo.MSP_VIEW_PROJ_TASKS_STD.TaskWork AS [Estimate at Complete],
dbo.MSP_VIEW_PROJ_TASKS_STD.TaskActualWorkProtected AS [Actual Work],
dbo.MSP_VIEW_PROJ_TASKS_STD.TaskRemainingWork AS [Estimate to Complete],
dbo.MSP_VIEW_PROJ_TASKS_STD.TaskBaselineWork AS BAC,
CASE WHEN dbo.MSP_VIEW_PROJ_TASKS_STD.TaskPercentComplete >= 100 THEN dbo.MSP_VIEW_PROJ_TASKS_STD.TaskBaselineWork
END AS EV,
dbo.MSP_VIEW_PROJ_TASKS_STD.TaskBaselineWork AS PV,
CASE WHEN dbo.MSP_VIEW_PROJ_TASKS_STD.TaskPercentComplete >= 100 THEN dbo.MSP_VIEW_PROJ_TASKS_STD.TaskActualWorkProtected
ELSE 0 END AS AC, dbo.MSP_VIEW_PROJ_TASKS_STD.TaskPercentComplete AS [% Complete],
DATEADD(day, 0, DATEDIFF(day, 0, dbo.MSP_VIEW_PROJ_TASKS_STD.TaskFinish)) AS Finish
FROM dbo.MSP_VIEW_PROJ_TASKS_STD INNER JOIN
dbo.MSP_VIEW_PROJ_TASKS_ENT ON
dbo.MSP_VIEW_PROJ_TASKS_STD.WPROJ_ID = dbo.MSP_VIEW_PROJ_TASKS_ENT.WPROJ_ID AND
dbo.MSP_VIEW_PROJ_TASKS_STD.TaskUniqueID = dbo.MSP_VIEW_PROJ_TASKS_ENT.ENT_TaskUniqueID INNER JOIN
dbo.MSP_WEB_PROJECTS ON dbo.MSP_VIEW_PROJ_TASKS_STD.WPROJ_ID = dbo.MSP_WEB_PROJECTS.WPROJ_ID INNER JOIN
dbo.MSP_VIEW_PROJ_PROJECTS_ENT ON
dbo.MSP_VIEW_PROJ_TASKS_STD.WPROJ_ID = dbo.MSP_VIEW_PROJ_PROJECTS_ENT.WPROJ_ID
WHERE (dbo.MSP_VIEW_PROJ_TASKS_STD.TaskSummary = 0)
)
AS derivedtbl_1 ON
TP.WPROJ_ID = derivedtbl_1.ProjectID CROSS JOIN
@result AS WeekEnds
WHERE (DATEADD(day, 0, DATEDIFF(day, 0, [Baseline Finish])) >= @Start AND DATEADD(day, 0, DATEDIFF(day, 0, [Baseline Finish])) <= @End) OR
(DATEADD(day, 0, DATEDIFF(day, 0, [Actual Finish])) >= @Start AND DATEADD(day, 0, DATEDIFF(day, 0, [Actual Finish])) <= @End) OR
(DATEADD(day, 0, DATEDIFF(day, 0, Finish)) >= @Start AND DATEADD(day, 0, DATEDIFF(day, 0, Finish)) <= @End)
)
AS WithWeekEnds
WHERE (BAC IS NOT NULL) OR (EV IS NOT NULL) OR (PV IS NOT NULL) OR
(AC IS NOT NULL) OR (FV IS NOT NULL) OR (FC IS NOT NULL)
GROUP BY WeekEndDate, ProjectID
)
AS EV_View INNER JOIN
dbo.MSP_WEB_PROJECTS ON
EV_View.ProjectID = dbo.MSP_WEB_PROJECTS.WPROJ_ID INNER JOIN
dbo.MSP_VIEW_PROJ_PROJECTS_STD ON
EV_View.ProjectID = dbo.MSP_VIEW_PROJ_PROJECTS_STD.WPROJ_ID INNER JOIN
dbo.MSP_VIEW_PROJ_PROJECTS_ENT ON
EV_View.ProjectID = dbo.MSP_VIEW_PROJ_PROJECTS_ENT.WPROJ_ID
ORDER BY dbo.MSP_WEB_PROJECTS.PROJ_NAME, EV_View.[Week Ending]

View 4 Replies View Related

Trigger To Update A Table On Insert Or Update

Feb 15, 2008



Hello

I've to write an trigger for the following action

When a entry is done in the table Adoscat79 having in the index field Statut_tiers the valeur 1 and a date in data_cloture for a customer xyz

all the entries in the same table where the no_tiers is the same as the one entered (many entriers) should have those both field updated

statut_tiers to 1
and date_cloture to the same date as entered

the same action has to be done when an update is done and the valeur is set to 1 for the statut_tiers and a date entered in the field date_clture

thank you for your help
I've never done a trigger before

View 14 Replies View Related







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