As a part of migration to .net we are redesigning sql server 7 database and moving it to sql server 2005. There are a lot of fields with dbnull value in the existing db. It would be nice to populate them with some default value while transfering data to the new datbase on sql server 2005. What is the best way to deal with the issue, are there any possible drawbacks and problems. Your input will be greatly appreciated.
Hello! Is there an easy way to deal with this situation below when reading in data from a SQL Database: int? myNullableColumn;myNullableColumn = Convert.ToInt32(datarow["datacolumn"]);
Where, ideally, 'myNullableColumn' would be 'null' if the value was 'DBNull.Value'. This does not work because Convert.ToInt32 will not convert 'DBNull.Value to null', but instead throws an error. Is there a built in funtion that does do this? Thanks!
Hi I have only been coding in .Net for about six months, and am not sure if this is a C# problem or an SQL one. I use the Data Access Application Block in my program.
I have two optional fields on my form (RangeFrom and RangeTo). If the user chooses not to enter data into these textboxes(textbox = ""), an entry on the db is created with null values. It works.
But sometimes the user wants to enter 0 as either an upper or lower end of a range. This is where my problem comes in. My program saves 0 as null too.
In my program I do a test on the textboxes and populate two float values in a business object (objQuestion) accordingly, like this:
//properties public float RangeFrom { get { return cvintRangeFrom; } set { cvintRangeFrom = value; } }
public float RangeTo { get { return cvintRangeTo; } set { cvintRangeTo = value; } }
// some code deleted for readability....
public int AddOption() { string cvstrSpName = "addOption"; SqlParameter [] cvstrStoredParams = SqlHelperParameterCache.GetSpParameterSet(gcstrConnectionString, cvstrSpName, true); //lines deleted for readability... //check if the optional fields have a value associated with them. if not, assign dbnull.value. cvstrStoredParams[4].Value=(cvintRangeFrom != Convert.ToSingle(null) ? cvintRangeFrom : (object)DBNull.Value); cvstrStoredParams[5].Value=(cvintRangeTo != Convert.ToSingle(null) ? cvintRangeTo : (object)DBNull.Value); //lines deleted for readability... SqlHelper.ExecuteNonQuery(gcstrConnectionString, CommandType.StoredProcedure, cvstrSpName, cvstrStoredParams); return(cvintOptionID = Convert.ToInt32(cvstrStoredParams[0].Value)); }
I use Convert.ToSingle when working with nulls (or possible nulls) because I get an error when I use float.parse for this.
The thing is, after this method AddOption has been executed, I test the value if the business object's rangefrom (that is where I entered 0) and display it on my form. I still shows a 0, but on my database table it is null!
objQuestion.AddOption(); //txtrangefrom.Text=""; on the next line I test the value in the business object... txtrangefrom.Text=objQuestion.RangeFrom.ToString(); // and this displays 0!!! //txtrangeto.Text=""; txtrangeto.Text=objQuestion.RangeTo.ToString();
So to me it seems the problem seems to be either the DAAB or on the SQL side, but hopefully somebody can prove me wrong! I was thinking that it could also be float.parse/Convert.ToSingle methods and have done various tests, but I am none the wiser... Any help or ideas will be greatly appreciated...
I haven't tested it, because at the moment I can't access my SQL database I know this is probably a stupid question, but...How can I test for DBNull when I'm using SqlDataReader.Item(string)? I use to check it using: if(!reader.IsDBNull(2)) ...But I have found that can not count on a particular ordinal reference because some of the stored procedures select the columns in different orders. can I do something like: if(reader["Column1"] != DBNull.Value)or with the reader["Column1"] throw an error because it is not found?? I too hate when people ask questions that they could test themselves...but I can't really test it at the moment. Any input would be greatly appreciated.
Hi! I was trying to use the ?? operator with an DBDatareader. eg: long lValue = Convert.ToInt32(objReader["ParentID"] ?? -1); which throws the following exception: "... Object cannot be cast from DBNull to other types."I think the reason is, that DBNull.Value isn´t actually null. Therefore I changed my code to: long lValue = objReader["ParentID"] != DBNull.Value ? Convert.ToInt32(objReader["ParentID"]) : -1; Is there a better way of doing this ? Can one use the ?? operator with a Datareader anyway? Thanks for your help! PS: sorry for my poor english.
Hi, I have built a few pages and a stored procedure and a class on the back of a SQL2000 dbase. and I get the following error:
Cast from type 'DBNull' to type 'String' is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Cast from type 'DBNull' to type 'String' is not valid.Source Error:
Line 111: Dim myWorkJobs As WorkJobsDATA = New WorkJobsDATA Line 112: Line 113: myWorkJobs.CustomerID = CStr(parameterCustomerID.Value) Line 114: myWorkJobs.WorkID = CStr(parameterWorkID.Value) Line 115: myWorkJobs.DateOfQuote = CStr(parameterDateOfQuote.Value).Trim() Source File: C:InetpubwwwrootCommerceComponentsWorkJobs.vb Line: 113
My Database has 1 line of data (for testing) and all fields are populated. I am Querying a column called IndividualID which has a value of 3425243 at the moment. This is hardcoded in the aspx.vb at the moment. ASPX VB: Public Class WorkRequest Inherits System.Web.UI.Page Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here End Sub Private Sub btnEnter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click 'for now, send this value (stored in dbase under individualID) to the querystring Dim IndividualID As String = "3425243" Response.Redirect("WorkRequestMain.aspx?IndividualID=" & IndividualID) End SubEnd Class
COMPONENTSWorkJobs.vb (This is the class file)
Imports SystemImports System.ConfigurationImports System.DataImports System.Data.SqlClient Namespace ASPNET.StarterKit.Commerce Public Class WorkJobsDATA Public CustomerID As String Public WorkID As String Public DateOfQuote As String Public QuoteAmount As String Public Title As Decimal Public FirstName As String Public Surname As String Public FirstLine As String Public District As String Public Town As String Public Postcode As String Public Telephone As String Public Requirements As String Public WorkRequired As String Public EmailAddress As String End Class Public Class WorkJobs Public Function GetWorkDetails(ByVal IndividualID As String) As WorkJobsDATA Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim myCommand As SqlCommand = New SqlCommand("SP_PendingQuotes", myConnection) ' Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure ' Add Parameters to SPROC Dim parameterIndividualID As SqlParameter = New SqlParameter("@IndividualID", SqlDbType.NVarChar, 50) parameterIndividualID.Value = IndividualID myCommand.Parameters.Add(parameterIndividualID) Dim parameterCustomerID As SqlParameter = New SqlParameter("@CustomerID", SqlDbType.BigInt, 8) parameterCustomerID.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterCustomerID) Dim parameterWorkID As SqlParameter = New SqlParameter("@WorkID", SqlDbType.NVarChar, 50) parameterWorkID.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterWorkID) Dim parameterDateOfQuote As SqlParameter = New SqlParameter("@DateOfQuote", SqlDbType.DateTime, 8) parameterDateOfQuote.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterDateOfQuote) Dim parameterQuoteAmount As SqlParameter = New SqlParameter("@QuoteAmount", SqlDbType.Money, 8) parameterQuoteAmount.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterQuoteAmount) Dim parameterTitle As SqlParameter = New SqlParameter("@Title", SqlDbType.NVarChar, 50) parameterTitle.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterTitle) Dim parameterFirstName As SqlParameter = New SqlParameter("@FirstName", SqlDbType.NVarChar, 50) parameterFirstName.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterFirstName) Dim parameterSurname As SqlParameter = New SqlParameter("@Surname", SqlDbType.NVarChar, 50) parameterSurname.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterSurname) Dim parameterFirstLine As SqlParameter = New SqlParameter("@FirstLine ", SqlDbType.NVarChar, 50) parameterFirstLine.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterFirstLine) Dim parameterDistrict As SqlParameter = New SqlParameter("@District", SqlDbType.NVarChar, 50) parameterDistrict.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterDistrict) Dim parameterTown As SqlParameter = New SqlParameter("@Town", SqlDbType.NVarChar, 50) parameterTown.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterTown) Dim parameterPostcode As SqlParameter = New SqlParameter("@Postcode", SqlDbType.NVarChar, 50) parameterPostcode.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterPostcode) Dim parameterTelephone As SqlParameter = New SqlParameter("@Telephone", SqlDbType.NVarChar, 50) parameterTelephone.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterTelephone) Dim parameterRequirements As SqlParameter = New SqlParameter("@Requirements", SqlDbType.NVarChar, 3500) parameterRequirements.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterRequirements) Dim parameterWorkRequired As SqlParameter = New SqlParameter("@WorkRequired", SqlDbType.NVarChar, 3500) parameterWorkRequired.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterWorkRequired) Dim parameterEmailAddress As SqlParameter = New SqlParameter("@EmailAddress", SqlDbType.NVarChar, 100) parameterEmailAddress.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterEmailAddress) myConnection.Open() myCommand.ExecuteNonQuery() myConnection.Close() parameterEmailAddress.Value.GetType() Dim myWorkJobs As WorkJobsDATA = New WorkJobsDATA myWorkJobs.CustomerID = CStr(parameterCustomerID.Value) myWorkJobs.WorkID = CStr(parameterWorkID.Value) myWorkJobs.DateOfQuote = CStr(parameterDateOfQuote.Value).Trim() myWorkJobs.Title = CStr(parameterTitle.Value).Trim() myWorkJobs.FirstName = CStr(parameterFirstName.Value).Trim() myWorkJobs.Surname = CStr(parameterSurname.Value).Trim() myWorkJobs.FirstLine = CStr(parameterFirstLine.Value).Trim() myWorkJobs.District = CStr(parameterDistrict.Value).Trim() myWorkJobs.Town = CStr(parameterTown.Value).Trim() myWorkJobs.Postcode = CStr(parameterPostcode.Value).Trim() myWorkJobs.Telephone = CStr(parameterTelephone.Value).Trim() myWorkJobs.Requirements = CStr(parameterRequirements.Value).Trim() myWorkJobs.WorkRequired = CStr(parameterWorkRequired.Value).Trim() myWorkJobs.EmailAddress = CStr(parameterEmailAddress.Value).Trim() Return myWorkJobs End Function End ClassEnd Namespace
Dear GroupI'm having a very weird problem. Any hints are greatly appreciated.I'm returning two values from a MS SQL Server 2000 stored procedure to myASP.NET Webapplication and store them in sessions.Like This:prm4 = cmd1.CreateParameterWith prm4..ParameterName = "@Sec_ProgUser_Gen"..SqlDbType = SqlDbType.VarChar..Size = 10..Direction = ParameterDirection.OutputEnd Withprm5 = cmd1.CreateParameterWith prm5..ParameterName = "@Sec_ProgUser_Key"..SqlDbType = SqlDbType.VarChar..Size = 10..Direction = ParameterDirection.OutputEnd With....cmd1.ExecuteNonQuery()....Session("Sec_ProgUser_Gen") = prm4.ValueSession("Sec_ProgUser_Key") = prm5.ValueBoth output parameters are declared as varchar(10) within the storedprocedure. If I run the stored procedure in SQL Analyzer, I'm getting astring value for each of them. E.g. @Sec_ProgUser_Gen is "1110011",@Sec_ProgUser_Key = "1100".Now the strange thing happens if I try to run the following code:Sub MyTest()Dim MyString1 As StringDim MyString2 As StringMyString1 = CStr(Session("Sec_ProgUser_Key"))....MyString2 = CStr(Session("Sec_ProgUser_Gen"))End SubIt fails in line 'MyString2 = CStr(Session("Sec_ProgUser_Gen"))' with Castfrom type 'DBNull' to type 'String' is not valid.I don't understand this. They are both the same, the only difference is thelength of the string. Help!Additional Information:The values for @Sec_ProgUser_XXX are created in the stored procedure with astatement like this:SET @Sec_ProgUser_Key = (SELECT Convert(varchar(1),Key_CanCreateKey) +Convert(varchar(1),Key_CanCreateTransaction) +Convert(varchar(1),Key_CanView) + Convert(varchar(1),Key_CanDelete) FROMi2b_proguser_securityprofile WHERE SecurityProfileID = @SecurityProfileID)The datatype of the source columns used to be bit then changed them toInteger as I thought this might cause the problem. (Although it shouldn't asthe values get converted to varchar without a problem in the storedprocedure. No fields contain NULL values, only 1 or 0.
I am developing the database application. This is a live database and is being used by the customer. I am to release a new version and I had to add new columns to fit the requirements DateStarted (DateTime), and TotalHours(Int) into a database table.There are already over a 1000 rows in this table.
When the customer wants to look at a record in this table and insert the value into the text boxes (Front-end), when it gets to the DateStarted or TotalHours it comes up with a error message:"
The value for column 'DateStarted' in table 'IncidentTask' is DBNull."The method for inserting is:
What are the possible solutions to this problem? Would it mean checking for a DBNULL before displaying in the textboxes? Or updating the new column rows with an date:
Code Snippet
UPDATE IncidentTask SET DateStarted = '1/1/2005' WHERE (DateStarted IS NULL)
Hi,I have a ShoppingCart class with a lot of properties (due to structure of a legacy Orders table). I have a ShoppingCart table also which contains a lot of the same fields as my orders table.There are a lot of fields (mostly ints) which have been initalised to 0 in my ShoppingCart class and then inserted into the ShoppingCart table when users add items to the cart. These fields are then inserted into the orders table upon check out. When i attempt to place a new record in the orders table from the ShoppingCart table, I am receiving a bunch of Foregin Key constraint errors due to all the int fields containing 0's.What i would like to do is initalise all the properites of my ShoppingCart object to DBNull.Value but of course I can't convert type 'System.DBNull' to 'int' and i can't set to 'null' either as int's are value types.I also tried:private Int32 _fieldname = Convert.ToInt32(DBNull.Value);This compiled but gave InvalidCastException runtime error.So the only option that i can think of is, as i build the parameter array to be sent to my stored procedure, test the value of each parameter, if it is 0 (or an empty string) then don't pass the actual field value but pass DBNull.Value instead.I REALLY don't want to do this as there are around 60 parameters being passed to this procedure and this will be time consuming and messy.Any suggestions would be most appreciated!ps If i could avoid having 60 parameters being passed I would...trust me!
Hi,I have a stored procedure which returns an integer indicating whether the operation has succeeded or failed. It does this by calling set @returnvalue = (0 or 1) then select @returnvalue as returnvalue in the stored procedure code. When I run the stored procedure, inputting a set of parameters as it expects, it does what it's supposed to do and outputs a table with a single row and a single column, called returnvalue, which has a value of either 1 or 0. When I run the stored procedure through a function in asp, using the exact same set of parameters, output the results as a data set and try and convert the return as an integer I get the following error: "Object Cannot be cast from DBNull from other types"The conversion code is ..return Convert.ToInt32(ds.Tables[0].Rows[0]["returnvalue"]);And if I change "returnvalue" to anything else (like "wibble" for example) then I get a different error telling me it can't find the column named "wibble". So the dataset definitely contains a table with a column in it called returnvalue, as you expect. But it's value is, apparently, DBNull instead of an integer.How come this works when called directly through SQL and fails when called through ASP? Can anyone help? This is really doing my head in!Cheers,Matt
Ok well i have a stored procedure that returns an integer between 1 and 5. My problem now is i want to check to see if the table will return NULL and if so i don't want to assign the value to my variable otherwise it'll trow an error. My code is listed below but i keep getting the error "Conversion from type 'DBNull' to type 'Integer' is not valid." i've also tried If getoptionpicked.Parameters("@optionpicked").Value = Nothing ThenIf getoptionpicked.Parameters("@optionpicked").Value Is system.dbnull Then below is the rest of the code If getoptionpicked.Parameters("@optionpicked").Value Is Nothing Then Else optionpicked = getoptionpicked.Parameters("@optionpicked").Value If optionpicked = 1 Then option1.Checked = True ElseIf optionpicked = 2 Then option2.Checked = True ElseIf optionpicked = 3 Then option3.Checked = True ElseIf optionpicked = 4 Then option4.Checked = True ElseIf optionpicked = 5 Then option5.Checked = True Else End If End If
I want restore database in my disk , but i cant . I've click and add from device. this is the screen. And when i click content , it show me this text :Â Object cannot be cast from DBNull to other types. (mscorlib) .Â
I have quite a few tables which allow NULL values. I have to struggle a lot with DBnull Exceptions :|example: col1,col2,... are all columns of type Integer and possibly NULL. var query = from person in table select new { person.col1, test = (int?) person.col2, person.col3, person.col4, ...}; As soon as my result encounters a DBNull value.. the whole query fails. This is really bad.How would I return the valid values.. and set the keys where there is no value to a null type? (e.g. int -> 0)I tried using "(int?)" but I'm not *really* sure what it does :-) Anyway.. it has no effect :-)
I'm creating an ISP for extractig data from a text file and put it in a database.
One of the fields in my textfile contains the value '0' or a date. If it's '0' it should be converted to the Null Value. The column in which it has to be saved is of type smalldatetime.
This is the code of my script where I want to check the value of the field in my textfile and convert it to a date or to Null.
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
If Row.cdDateIn = "" Or Row.cdDateIn= "0" Then
Row.cdDateInCorr = CDate(DBNull.Value)
ElseIf Row.cdDateIn_IsNull Then
Row.cdDateInCorr = CDate(DBNull.Value)
Else
Row.cdDateInCorr = CDate(Row.cdDateIn)
End If
End Sub
The error that I get is:
Validation error. Extract FinCD: Conversion of cdDateIn [753]: Eroor 30311: Value of type 'System.DBNull' cannot ben converted to 'Date'.
Hello Friends How are you?? Friends i am getting problem in SQL Server 2005. I am deployng web application on production server as well as Databse also. In production server i inserted new field in all tables which is rowguid and its type is uniqueidentifier. The default binding for this field is newsequentialid(). In some pages it works ok but in some places it generates error like 'Conversion from type 'DBNull' to type 'String' is not valid'. Can anybody help me to solve this problem. Its urgent so plz reply me as soon as possible. I'll be very thankfull to you. Thanks in Advance. Regards,
Hi, I have developed a custom server control for .NET Framework 2.0. The server control has a property named BinaryData of type byte[]. I marked this property to be data bindable. Now, I have varbinary(Max) type of field in my SQL Database and I have used SQLDataSource and bound this varbinary(Max) field with the property BinaryData (byte[]) of my control. It is working fine as long as the data value is not NULL. Now, In my control, I have handled the NULL value so that no Exception is thrown. Still, when I bind this property using the SQLDataSource, I get Error "Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'." I am not sure if I can do anything to stop this erro within my control. If it is not possible from the control, then what is the workaround that I can do in my ASPX page in order to stop this error ? Thanks a lot in advance.
hello friends my one insert code lines is below :) what does int32 mean ? AND WHAT IS DIFFERENT BETWEEN ONE CODE LINES AND SECOND CODE LINES :)Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString) Dim cmd As New SqlCommand("Insert into table1 (UserId) VALUES (@UserId)", conn) 'you should use sproc instead cmd.Parameters.AddWithValue("@UserId", textbox1.text) 'your value Try conn.Open()Dim rows As Int32 = cmd.ExecuteNonQuery() conn.Close()Trace.Write(String.Format("You have {0} rows inserted successfully!", rows.ToString())) Catch sex As SqlExceptionThrow sex Finally If conn.State <> Data.ConnectionState.Closed Then conn.Close() End If End Try MY SECOND INSERT CODE LINES IS BELOWDim SglDataSource2, yeni As New SqlDataSource() SglDataSource2.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString SglDataSource2.InsertCommandType = SqlDataSourceCommandType.Text SglDataSource2.InsertCommand = "INSERT INTO urunlistesi2 (kategori1) VALUES (@kategori1)" SglDataSource2.InsertParameters.Add("kategori1", kategoril1.Text)Dim rowsaffected As Integer = 0 Try rowsaffected = SglDataSource2.Insert()Catch ex As Exception Server.Transfer("yardim.aspx") Finally SglDataSource2 = Nothing End Try If rowsaffected <> 1 ThenServer.Transfer("yardim.aspx") ElseServer.Transfer("urunsat.aspx") End If
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.
An insert statement was not inserting all the data into a table. Found it very strange as the other fields in the row were inserted. I ran SQL profiler and found that sql statement had all the fields in the insert statement but some of the fields were not inserted. Below is the sql statement which is created dyanmically by a asp.net C# class. The columns which are not inserted are 'totaltax' and 'totalamount' ...while the 'shipto_name' etc...were inserted.there were not errors thrown. The sql from the code cannot be shown here as it is dynamically built referencing C# class files.It works fine on another test database which uses the same dlls. The only difference i found was the difference in date formats..@totalamount=1625.62,@totaltax=125.62are not inserted into the database.Below is the statement copied from SQL profiler.exec sp_executesql N'INSERT INTO salesorder(billto_city, billto_country, billto_line1, billto_line2, billto_name,billto_postalcode, billto_stateorprovince, billto_telephone, contactid, CreatedOn, customerid, customeridtype,DeletionStateCode, discountamount, discountpercentage, ModifiedOn, name, ordernumber,pricelevelid, salesorderId, shipto_city, shipto_country,shipto_line1, shipto_line2, shipto_name, shipto_postalcode, shipto_stateorprovince,shipto_telephone, StateCode, submitdate, totalamount,totallineitemamount, totaltax ) VALUES(@billto_city, @billto_country, @billto_line1, @billto_line2,@billto_name, @billto_postalcode, @billto_stateorprovince, @billto_telephone, @contactid, @CreatedOn, @customerid,@customeridtype, @DeletionStateCode, @discountamount,@discountpercentage, @ModifiedOn, @name, @ordernumber, @pricelevelid, @salesorderId,@shipto_city, @shipto_country, @shipto_line1, @shipto_line2,@shipto_name, @shipto_postalcode, @shipto_stateorprovince, @shipto_telephone,@StateCode, @submitdate, @totalamount, @totallineitemamount, @totaltax)',N'@billto_city nvarchar(8),@billto_country nvarchar(13),@billto_line1 nvarchar(3),@billto_line2 nvarchar(4),@billto_name nvarchar(15),@billto_postalcode nvarchar(5),@billto_stateorprovince nvarchar(8),@billto_telephone nvarchar(3),@contactid uniqueidentifier,@CreatedOn datetime,@customerid uniqueidentifier,@customeridtype int,@DeletionStateCode int,@discountamount decimal(1,0),@discountpercentage decimal(1,0),@ModifiedOn datetime,@name nvarchar(33),@ordernumber nvarchar(18),@pricelevelid uniqueidentifier,@salesorderId uniqueidentifier,@shipto_city nvarchar(8),@shipto_country nvarchar(13),@shipto_line1 nvarchar(3),@shipto_line2 nvarchar(4),@shipto_name nvarchar(15),@shipto_postalcode nvarchar(5),@shipto_stateorprovince nvarchar(8),@shipto_telephone nvarchar(3),@StateCode int,@submitdate datetime,@totalamount decimal(6,2),@totallineitemamount decimal(6,2),@totaltax decimal(5,2)',@billto_city=N'New York',@billto_country=N'United States',@billto_line1=N'454',@billto_line2=N'Road',@billto_name=N'Hillary Clinton',@billto_postalcode=N'10001',@billto_stateorprovince=N'New York',@billto_telephone=N'124',@contactid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@CreatedOn=''2008-04-18 13:37:12:013'',@customerid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@customeridtype=2,@DeletionStateCode=0,@discountamount=0,@discountpercentage=0,@ModifiedOn=''2008-04-18 13:37:12:013'',@name=N'E-Commerce Order (Before billing)',@ordernumber=N'BRKV-CC-OKRW5764YS',@pricelevelid='B74DB28B-AA8F-DC11-B289-000423B63B71',@salesorderId='9CD0E11A-5A6D-4584-BC3E-4292EBA6ED24',@shipto_city=N'New York',@shipto_country=N'United States',@shipto_line1=N'454',@shipto_line2=N'Road',@shipto_name=N'Hillary Clinton',@shipto_postalcode=N'10001',@shipto_stateorprovince=N'New York',@shipto_telephone=N'124',@StateCode=0,@submitdate=''2008-04-18 14:37:10:140'',@totalamount=1625.62,@totallineitemamount=1500.00,@totaltax=125.62
Hello I have a problem with setting relations properly when inserting data using adonet. Already have searched for a solutions, still not finding a mistake... Here's the sql management studio diagram :
and that causes (at line 67):"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Question_SurveyTemplate". The conflict occurred in database "ankietyzacja", table "dbo.SurveyTemplate", column 'id'. The statement has been terminated. at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount) at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount) at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping) at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping) at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable) at AnkietyzacjaWebService.Service1.createSurveyTemplate(Object[] o) in J:\PL\PAI\AnkietyzacjaWebService\AnkietyzacjaWebServicece\Service1.asmx.cs:line 397"
Could You please tell me what am I missing here ? Thanks a lot.
Is there a way to avoid entering column names in the excel template for me to create an excel file froma dynamic excel using openrowset. I have teh following code but it works fien when column names are given ahead of time. If I remove the column names from the template and just to Select * from the table and Select * from sheet1 then it tells me that column names donot match. Server: Msg 213, Level 16, State 5, Line 1Insert Error: Column name or number of supplied values does not match table definition. here is my code... SET @sql1='select * from table1'SET @sql2='select * from table2' IF @File_Name = '' Select @fn = 'C:Test1.xls' ELSE Select @fn = 'C:' + @File_Name + '.xls' -- FileCopy command string formation SELECT @Cmd = 'Copy C:TestTemplate1.xls ' + @fn -- FielCopy command execution through Shell Command EXEC MASTER..XP_CMDSHELL @cmd, NO_OUTPUT -- Mentioning the OLEDB Rpovider and excel destination filename set @provider = 'Microsoft.Jet.OLEDB.4.0' set @ExcelString = 'Excel 8.0;HDR=yes;Database=' + @fn exec('insert into OPENrowset(''' + @provider + ''',''' + @ExcelString + ''',''SELECT * FROM [Sheet1$]'') '+ @sql1 + '') exec('insert into OPENrowset(''' + @provider + ''',''' + @ExcelString + ''',''SELECT * FROM [Sheet2$]'') '+ @sql2 + ' ')
Hello, I'm new to the forum and new to SQL, ASP.NET, etc. I am creating an intranet site for my company in VS 2005 and have run into a very annoying problem that I can't seem to solve. I have tried Googling it and came up empty. I have a database in SQL Express 2005 and my website will be accessing several tables within the database. I can retrieve info just fine and I can update, delete, etc just fine using gridview or other prebuilt tools, but when I add a few text boxes and wire a button to the SqlDataSource.Insert() command, I get a new record that is full of null values except for the identity key I have set. The kicker is that I am also using a master page and when I duplicate the web page without the master page link, everything works just fine. The following snippets show what I'm doing:<InsertParameters><asp:FormParameter Name="Name" Type="String" FormField="txtName" /><asp:FormParameter Name="Location" Type="String" FormField="ddlLocation" /><asp:FormParameter Name="Issue" Type="String" FormField="txtProblem" /></InsertParameters>Of course I match the formfields to the text boxes, create an onclick event for my button, the sqldatasource is configured correctly, it just doesn't work with the master page no matter what I do. Any help would be appreciated. Thanks
On my site users can register using ASP Membership Create user Wizard control. I am also using the wizard control to design a simple question and answer form that logged in users have access to. it has 2 questions including a text box for Q1 and dropdown list for Q2. I have a table in my database called "Players" which has 3 Columns UserId Primary Key of type Unique Identifyer PlayerName Type String PlayerGenre Type Sting
On completing the wizard and clicking the finish button, I want the data to be inserted into the SQl express Players table. I am having problems getting this to work and keep getting exceptions. Be very helpful if somebody could check the code and advise where the problem is??
To match the answers to the user I get the UserId and insert this into the database to.protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e) { SqlDataSource DataSource = (SqlDataSource)Wizard1.FindControl("InsertArtist1"); MembershipUser myUser = Membership.GetUser(this.User.Identity.Name); Guid UserId = (Guid)myUser.ProviderUserKey;String Gender = ((DropDownList)Wizard1.FindControl("PlayerGenre")).SelectedValue; DataSource.InsertParameters.Add("UserId", UserId.ToString());DataSource.InsertParameters.Add("PlayerGenre", Gender.ToString()); DataSource.Insert();
This problem is being seen on SQL 2005 SP2 + cumulative update 4
I am currently successfully using the output clause of an insert statement to return the identity values for inserted rows into a table variable
I now need to add an "instead of insert" trigger to the table that is the subject of the insert.
As soon as I add the "instead of insert" trigger, the output clause on the insert statement does not return any data - although the insert completes successfully. As a result I am not able to obtain the identities of the inserted rows
Note that @@identity would return the correct value in the test repro below - but this is not a viable option as the table in question will be merge replicated and @@identity will return the identity value of a replication metadata table rather than the identity of the row inserted into my_table
Note also that in the test repro, the "instead of insert" trigger actually does nothing apart from the default insert, but the real world trigger has additional code.
To run the repro below - select each of the sections below in turn and execute them 1) Create the table 2) Create the trigger 3) Do the insert - note that table variable contains a row with column value zero - it should contain the @@identity value 4) Drop the trigger 5) Re-run the insert from 3) - note that table variable is now correctly populated with the @@identity value in the row
I need the behaviour to be correct when the trigger is present
GO /************************************************ 2) - Create the trigger ************************************************/ CREATE TRIGGER [dbo].[trig_my_table__instead_insert] ON [dbo].[my_table] INSTEAD OF INSERT AS BEGIN
INSERT INTO my_table ( forename, surname) SELECT forename, surname FROM inserted
END
/************************************************ 3) - Do the insert ************************************************/
INSERT INTO my_table ( forename , surname ) OUTPUT inserted.my_table_id INTO @my_insert VALUES( @forename , @surname )
select @@identity -- expect this value in @my_insert table select * from @my_insert -- OK value without trigger - zero with trigger
/************************************************ 4) - Drop the trigger ************************************************/
drop trigger [dbo].[trig_my_table__instead_insert] go
/************************************************ 5) - Re-run insert from 3) ************************************************/ -- @my_insert now contains row expected with identity of inserted row -- i.e. OK
I decided to change over from Microsoft Access Database file to the New SQLServerCe Compact edition. Although the reading of data from the database is greatly improved, the inserting of the new rows is extremely slow.
I was getting between 60 to 70 rows per sec using OLEDB and an Access Database but now only getting 14 to 27 rows per sec using SQLServerCe.
I have tried the below code changes and nothing seams to increase the speed, any help as I would prefer to use SQLServerCe as the database is much smaller and I€™m use to SQL Commands.
Details: VB2008 Pro .NET Frameworks 2.0 SQL Compact Edition V3.5 Encryption = Engine Default Database Size = 128Mb (But needs to be changes to 999Mbs)
Where Backup_On_Next_Run, OverWriteQuick, CompressAns are Booleans, all other column sizes are nvarchar and size 10 to 30 expect for Full Folder Address size 260
14 to 20 rows per second (Was 60 to 70 when using OLEDB Access)
TRY 2
Using Record Sets
Private Sub InsertRecordsIntoSQLServerce(ByVal Group_Name1 As String, ByVal Full_Folder_Address1 As String, ByVal File1 As String, ByVal File_Size_KB1 As String, ByVal Schedule_To_Run1 As String, ByVal Backup_Time1 As String, ByVal Last_Run1 As String, ByVal Result1 As String, ByVal Last_Modfied1 As String, ByVal Latest_Modfied1 As String, ByVal Backup_On_Next_Run1 As Boolean, ByVal Total_Backup_Times1 As String, ByVal Server_File_Number1 As String, ByVal Server_Number1 As String, ByVal File_Break_Down1 As String, ByVal No_Of_Servers1 As String, ByVal Full_File_Address1 As String, ByVal OverWriteQuick As Boolean, ByVal CompressAns As Boolean)
cmd.CommandText = "SELECT * FROM BackupDatabase" cmd.ExecuteNonQuery() Dim rs As SqlCeResultSet = cmd.ExecuteResultSet(ResultSetOptions.Updatable Or ResultSetOptions.Scrollable)
Dim rec As SqlCeUpdatableRecord = rs.CreateRecord()
rec.SetString(1, Group_Name1) rec.SetString(2, Full_Folder_Address1) rec.SetString(3, File1) rec.SetSqlString(4, File_Size_KB1) rec.SetSqlString(5, Schedule_To_Run1) rec.SetSqlString(6, Backup_Time1) rec.SetSqlString(7, Last_Run1) rec.SetSqlString(8, Result1) rec.SetSqlString(9, Last_Modfied1) rec.SetSqlString(10, Latest_Modfied1) rec.SetSqlBoolean(11, Backup_On_Next_Run1) rec.SetSqlString(12, Total_Backup_Times1) rec.SetSqlString(13, Server_File_Number1) rec.SetSqlString(14, Server_Number1) rec.SetSqlString(15, File_Break_Down1) rec.SetSqlString(16, No_Of_Servers1) rec.SetSqlString(17, Full_File_Address1) rec.SetSqlBoolean(18, OverWriteQuick) rec.SetSqlBoolean(19, CompressAns) rs.Insert(rec) Catch e As Exception MessageBox.Show(e.Message) Finally conn.Close() End Try End Sub
€™20 to 24 rows per sec
TRY 3
Using SQL Commands Direct
Private Sub InsertRecordsIntoSQLServerce(ByVal Group_Name1 As String, ByVal Full_Folder_Address1 As String, ByVal File1 As String, ByVal File_Size_KB1 As String, ByVal Schedule_To_Run1 As String, ByVal Backup_Time1 As String, ByVal Last_Run1 As String, ByVal Result1 As String, ByVal Last_Modfied1 As String, ByVal Latest_Modfied1 As String, ByVal Backup_On_Next_Run1 As Boolean, ByVal Total_Backup_Times1 As String, ByVal Server_File_Number1 As String, ByVal Server_Number1 As String, ByVal File_Break_Down1 As String, ByVal No_Of_Servers1 As String, ByVal Full_File_Address1 As String, ByVal OverWriteQuick As Boolean, ByVal CompressAns As Boolean)
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.
I am currently using openquery to insert data into a SQL 2000 database from a Lotus Notes database. The Lotus database is a linked server with a datasource named CLE_CARS_SF. My SQL table is called Webcases.
The query below works well because the table's columns are even in both databases:
Insert into Webcases select * from openquery(CLE_CARS_SF, 'Select * from Web_Cases')
I am moving this over to SQL 2005. The query works well, but I want to add a column to the Webcases SQL database and manually insert a value along with the openquery values.
My insert statement above no longer works because the column numbers don't match.
In a nutshell I would like a way to combine the following queries:
Insert into Webcases select * from openquery(CLE_CARS_SF, 'Select * from Web_Cases')
Insert into Webcases (insurancetype) Values ('SF')