Showing posts with label columns. Show all posts
Showing posts with label columns. Show all posts

Saturday, February 25, 2012

DataAdapter Update Problems

Hi, I am populating a datagrid with data from one sql table, I add additional columns and then wish to write it back out to another table. I have written the following code to acheive this, however it keeps throwing the follwing exception - "Update requites a valid UpdateComman when passed a DataRow collection with modified rows"

I've looked and I can see what the problem is, can anybody help please?

Private Sub FillData()'SQL connectionMe.sqlconnection =New System.Data.SqlClient.SqlConnectionMe.sqlconnection.ConnectionString = ConfigurationSettings.AppSettings("CuroConnection")Dim sqlAs String If Request("action") ="gen"Then sql ="select item from tblPickList where GroupName ='xxx'AND Category = '" & Category2 & "' ORDER BY item ASC" ElseIf Request("action") = "fav" Then sql = "select identifiertext as item from tblfavourites where HRID =" & Session("hrid") & " and type = 3 ORDER BY identifiertext ASC" ElseIf Request("action") = "spec" Then sql = "select item from tblPickList where GroupName ='" & GroupID & "' AND Category = '" & Category2 & "' ORDER BY item ASC"End If ds =New DataSet da =New SqlClient.SqlDataAdapter(sql, sqlconnection)Try sqlconnection.Open() da.Fill(ds,"tblPickListTemp") sqlconnection.Close()Catch exAs Exception sqlconnection.Close()End Try ds.Tables(0).Columns.Add("HRID") ds.Tables(0).Columns.Add("Flag")'may possibly add a favourites column here at a later date to ensure no duplicationDim drAs DataRowFor Each drIn ds.Tables("tblPickListTemp").Rows dr("HRID") = Session("hrid") dr("Flag") = 0Next DgrdFavourites.DataSource = ds DgrdFavourites.DataBind()End Sub Public Sub CreateTempRecords()'SQL connectionMe.sqlconnection =New System.Data.SqlClient.SqlConnectionMe.sqlcommand =New System.Data.SqlClient.SqlCommandMe.da =New SqlClient.SqlDataAdapterMe.sqlconnection.ConnectionString = ConfigurationSettings.AppSettings("CuroConnection")Dim sqlAs String sql ="Insert into tblPickListTemp (Item, HRID, Flag) values (@.Item, @.HRID, @.Flag)" sqlcommand.CommandText = sql sqlcommand.Connection = sqlconnection sqlcommand.Parameters.Add("@.Item","Item") sqlcommand.Parameters.Add("@.HRID","HRID") sqlcommand.Parameters.Add("@.Flag","Flag") da.InsertCommand = sqlcommand da.Update(ds.Tables(0))End Sub

Hello Naimh,

Your program retrieves records from the database, you modify them and try to update the records in the database.

In that case you need to add an UpdateCommand to your SqlDataAdapter.

The Update statement will than handle new rows and modified rows.

Jeroen Molenaar.

|||I thought that was what I was doing with the da.InsertCommand on the 2nd to last line.I'm not sure I've really got to grips with the dataadapter syntax, could you show me please?|||

The InsertCommand you use is correct. But you are not adding new rows to the table, so you need also the UpdateCommand.

sql = "Update tblPickList Set HRID = @.HRID, Flag = @.Flag where Item = @.Item"

// Add the parameters here ...

sqlcommand.CommandText = sql

da.UpdateCommand = sqlcommand

// etc.

Hope you get it working now.

Jeroen Molenaar.

|||

jeroenm:

The InsertCommand you use is correct. But you are not adding new rows to the table, so you need also the UpdateCommand.

Okay really confused now, as that is exactly what I want to do, I populate the dataset from one table, manipulate it in the dataset and then Insert entirely new row's into a completely different table, erk! I shall give your suggestion a try but I have to fess up to being none the wiser.|||

jeroenm:

sql?= "Update tblPickListTemp Set HRID = @.HRID, Flag = @.Flag where Item = @.Item"

See now this is never going to work for me, tblPickListTemp ( the table I want to insert rows into) at the start of this process is empty, I cannot update and set fields to new values when no records currently exist.Ah well back to the drawing board, thanks anyway.|||

Do you have an AcceptChanges statement somewhere before the data is saved to the database?

When you modify the dataset after AcceptChanges, the tableadapter thinks it needs an Update statement in stead of an Insert statement.

Jeroen Molenaar.

|||No I am afraid I don't, all the code is in the snippet above. It's most confusing. I have also ensured that the primary key is set in the recipient table, which is another common problem which throws this error. I am at a real loss and almost at the point of scrapping the whole thing and taking a different approach, it's just that if I could have got this to work it would have been less trips to the Db and a lot less spaghetti code.|||

You can add some ASP.NET code. Perhaps this gives another clue.

|||

<form id="Form1" method="post" runat="server"><TABLE id="Table2" cellSpacing="0" cellPadding="0" width="280" align="center" border="0"><TR height="24"><TD class="fntmed" style="WIDTH: 280px" background="../images/header.jpg">         PickList</TD></TR><TR><TD class="fntnorm" style="WIDTH: 280px; HEIGHT: 36px"><IMG height="6" src="../images/6pixspacer.gif"><br><asp:image id="imgLine" runat="server" Width="260px" ImageUrl="../Images/line.jpg"></asp:image></TD></TR><TR><TD><div style="OVERFLOW: auto; WIDTH: 270px; POSITION: static; HEIGHT: 190px"><asp:DataGrid id="DgrdFavourites" autogeneratecolumns="False" BackColor="#ffffff" showheader="False"OnItemCommand="DgrdFavourites_ItemCommand" runat="server" Width="256px" Height="25px" BorderWidth="0"CssClass="fntsmall" AlternatingItemStyle-CssClass="fntsmall"><AlternatingItemStyle BackColor="#e2eaee" /><Columns><asp:BoundColumn DataField="Item" /><asp:templatecolumn ItemStyle-HorizontalAlign="Right"><ItemTemplate><asp:button CssClass="buttonlike" Text="Select" commandname="Select" runat="server" ID="btnSelect" /></ItemTemplate></asp:templatecolumn><asp:templatecolumn ItemStyle-HorizontalAlign="Right"><ItemTemplate><asp:button CssClass="buttonlike" Text="Favourite" runat="server" commandname="Add" ID="btnAdd" /></ItemTemplate></asp:templatecolumn></Columns></asp:DataGrid></div></TD></TR></TABLE><asp:Label ID="oops" Runat="server"></asp:Label></form></body>
That the entirety of the front end code, basically at page load inside a "If not Is Postback" the Filldata() method is invoked followed by the CreateTempData() method. Not a lot to it really.|||

Hello Naimh,

Sorry, but I've been moving you into the wrong direction. My first idea was correct, but I didn't read your code properly.Embarrassed

When you call FillData the dataset ds is filled from the table tblPickList. In FillData you add 2 columns and modify all rows with the session HRID. At this stage your rows have the status Modified in the dataset ds. (This generates the error message when calling da.Update())

Before "DgrdFavourites.DataSource = ds" you can enter the command ds.AcceptChanges(). All modifications are accepted and no update statement will be generated by the dataadapter.

The second thing is make some changes to CreateTempRecords. Create a new dataset dstemp as a copy of ds. After that insert the rows from ds into the new dataset dstemp, for example with a foreach construction. Now the new dataset is ready for the insert statement that you have written in CreateTempRecords(). Change da.Update(ds.Tables(0)) into da.Update(dstemp.Tables(0)).

Now your code should do the job!

Jeroen Molenaar.

Friday, February 24, 2012

Data types

I need to export the name of certain user tables along with the names of their columns and which type the column contains ie. varchar / integer and so on. I can figure out the table and column names - but how do i retrieve information about the data-types in each column ?

My query so far:

--------
select obj.Name as Tbl,Col.Name as Col
from sysobjects obj, syscolumns col
where obj.xtype='U' and obj.Name like 'netop%' and obj.id=col.id
--------

Thx. in advanceSELECT A.TABLE_NAME, B.COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.TABLES AS A
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS B
ON A.TABLE_NAME = B.TABLE_NAME
WHERE A.TABLE_NAME = 'yourTable'

Very useful views and I strongly recommend that your read more about them on BOL.|||WOW - that was fast - thanks a lot|||Beware of objects with the same name and different owners! Include a join on TABLE_SCHEMA to be safe:

SELECT A.*, A.TABLE_NAME, B.COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.TABLES AS A
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS B
ON A.TABLE_NAME = B.TABLE_NAME
AND A.TABLE_SCHEMA = B.TABLE_SCHEMA

blindman|||Good point and well spotted.

Sunday, February 19, 2012

Data Type for Qty and Revenue

What is the data type used for "Quantity" columns (which might have 0 to 2 decimals) and Revenue columns (which might have 0 to 4 decimals) ?how about

DECLARE @.quantity decimal(15,2), @.revenue money

??|||Whats the decimal precision for Money ?|||Originally posted by forXLDB
Whats the decimal precision for Money ?

I only needed 0 to 2 decimals in the revenue column.|||Money is 4 position decimal...

use the decimal...and use books online...look up datatypes...

Transact-SQL Reference


Data Types
In Microsoft SQL Server, each column, local variable, expression, and parameter has a related data type, which is an attribute that specifies the type of data (integer, character, money, and so on) that the object can hold. SQL Server supplies a set of system data types that define all of the types of data that can be used with SQL Server. The set of system-supplied data types is shown below.

User-defined data types, which are aliases for system-supplied data types, can also be defined. For more information about user-defined data types, see sp_addtype and Creating User-defined Data Types.

When two expressions that have different data types, collations, precision, scale, or length are combined by an operator:

The data type of the resulting value is determined by applying the rules of data type precedence to the data types of the input expressions. For more information, see Data Type Precedence.

If the result data type is char, varchar, text, nchar, nvarchar, or ntext, the collation of the result value is determined by the rules of collation precedence. For more information, see Collation Precedence.

The precision, scale, and length of the result depend on the precision, scale, and length of the input expressions. For more information, see Precision, Scale, and Length.
SQL Server provides data type synonyms for SQL-92 compatibility. For more information, see Data Type Synonyms.

Exact Numerics
Integers
bigint

Integer (whole number) data from -2^63 (-9223372036854775808) through 2^63-1 (9223372036854775807).

int

Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).

smallint

Integer data from 2^15 (-32,768) through 2^15 - 1 (32,767).

tinyint

Integer data from 0 through 255.

bit
bit

Integer data with either a 1 or 0 value.

decimal and numeric
decimal

Fixed precision and scale numeric data from -10^38 +1 through 10^38 1.

numeric

Functionally equivalent to decimal.

money and smallmoney
money

Monetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit.

smallmoney

Monetary data values from -214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth of a monetary unit.

Approximate Numerics
float

Floating precision number data from -1.79E + 308 through 1.79E + 308.

real

Floating precision number data from -3.40E + 38 through 3.40E + 38.

datetime and smalldatetime
datetime

Date and time data from January 1, 1753, through December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds.

smalldatetime

Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute.

Character Strings
char

Fixed-length non-Unicode character data with a maximum length of 8,000 characters.

varchar

Variable-length non-Unicode data with a maximum of 8,000 characters.

text

Variable-length non-Unicode data with a maximum length of 2^31 - 1 (2,147,483,647) characters.

Unicode Character Strings
nchar

Fixed-length Unicode data with a maximum length of 4,000 characters.

nvarchar

Variable-length Unicode data with a maximum length of 4,000 characters. sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128) and is used to reference database object names.

ntext

Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823) characters.

Binary Strings
binary

Fixed-length binary data with a maximum length of 8,000 bytes.

varbinary

Variable-length binary data with a maximum length of 8,000 bytes.

image

Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes.

Other Data Types
cursor

A reference to a cursor.

sql_variant

A data type that stores values of various SQL Server-supported data types, except text, ntext, timestamp, and sql_variant.

table

A special data type used to store a result set for later processing .

timestamp

A database-wide unique number that gets updated every time a row gets updated.

uniqueidentifier

A globally unique identifier (GUID).|||Originally posted by Brett Kaiser
Money is 4 position decimal...

use the decimal...and use books online...look up datatypes...

Thx for the quick response.

But, if I need to store only 2 decimals for revenue, is there any way other than using convert function|||Originally posted by Brett Kaiser
ummm...

DECLARE @.quantity decimal(15,2), @.revenue decimal(15,2)

DATA TYPE definitions

I am setting up columns in a data table. Where can I find the definitions and uses for all the items on the DATA TYPE drop down list such asntext andnchar? The data type list is also found under column properties general section.

SQL Server Books On Line is the best resource, so far. It shouldalready have been installed along with the database if you haveselected the option during installation. If not its a free downloadfrom MS website.
|||Thanks.
Yes, SQL is installed.
Will a book on SQL help me understand all of the other settings under column properties?
Are you talking about MS SQL?|||

When you install SQL Server you also installed the BOL(books online) the best documentation in the RDBMS(relational database management systems) business. The following are the data type and explanation based on my experience. Hope this helps.

Bigint, Int, Smallint, Tinyint and Bit(proprietry boolean) so three valued as ANSI SQL boolean true, fasle and Null(unknown) not an empty string.

Decimal and Numeric
You can set precision and scale.


Money and Smallmoney
There are known rounding issues going back to 1999 that I know better to use Decimal or Numeric


Float and Real floating point data types used for only T-SQL quantitative functions that are based on Float but cast or convert results to Decimal or Numeric to store.


Char fixed length ASCII character 8000 max, Varchar varaible length ASCII character 8000 max can overflow and Text can grow to 2gig in size ASCII text.


NChar fixed length Unicode 4000 max, NVarchar unicode variable length character 4000 max, NText unicode text can grow to 1gig in size because unicode types are multibytes.


Binary fixed length binary data 8000 max
Varbinary variable length binary data 8000 max
Image variable length binary data can grow to 2gig in size also known as BLOB(binary large objects)


Other Data Types
Cursor
A reference to a cursor.


Sql_variant

A data type that stores values of various SQL Server-supported data types, except text, ntext, timestamp, and sql_variant.


Table

A special data type used to store a result set for later processing .


Timestamp
A derived data type used by SQL Server internally cannot move with your data but you can creat fake one with datetime and trigger. A database-wide unique number that gets updated every time a row gets updated.


Uniqueidentifier/NewID
16 bytes data type to be used carefully

A globally unique identifier (GUID).


IDENTITY is a property to the column using it.

|||

Thank you for your time and info. That is helpful info.
Where can I find the books online?
I have installed Visual Web Developer Express 05 and SQL Server 05.

Thanks

|||

Hi
The links below the first holds a copy of the data type page in SQL Server 2000 and download the SQL Server 2005 BOL(books online) from the second link. Hope this helps.
http://www.mssqlcity.com/Articles/General/choose_data_type.htm


http://www.microsoft.com/downloads/details.aspx?familyid=BE6A2C5D-00DF-4220-B133-29C1E0B6585F&displaylang=en

|||

Yes, this helped a lot. Thanks.
I just downloaded the BOL for SQL 05.
Is there a list of other BOL for other subjects? (Especially Visual Web Developer Express 05)
I searched the MS download site, but I did not find any other books.

|||

Try the link below to download the .NET 2.0 SDK software development kit and take the visual web developer tour. Hope this helps.

http://www.microsoft.com/downloads/details.aspx?familyid=FE6F2099-B7B4-4F47-A244-C96D69C35DEC&displaylang=en

http://msdn.microsoft.com/vstudio/express/vwd/default.aspx

|||

HAving a few problems with BLOB and Oracle, when creating new automated DataSet, VS2005 believes those are 4000 of length.

http://alpascual.com/blog/al/archive/2006/07/25/238.aspx

Any advice?

Cheers

Al

|||

The links below covers all the Oracle data types and the .NET data types with code sample to get you started. Post again if you still need help.

http://msdn2.microsoft.com/en-us/library/system.data.oracleclient.oraclelob.aspx

http://msdn2.microsoft.com/en-us/library/system.data.oracleclient.oracletype.aspx

Friday, February 17, 2012

Data type Conversion during update ...

I am trying to update a row in a table. To my SP, I send an XML string.
One of the columns I am trying to update is of type "Bit" and the value I am
getting from my app is either "true" or "false". This is the general
structure of sp:
UPDATE x
SET x.isEmployee = xmlEmp.isEmployee
WHERE ...
I tried the following to convert my xmlEmp.isEmployee to "BIT" ...
SET x.isEmployee = CASE WHEN xmlEmp.isEmployee='false' THEN 0 ELSE 1 END
SET x.isEmployee = CASE WHEN xmlEmp.isEmployee='false' THEN CAST(0 AS BIT)
ELSE CAST(1 AS BIT) END
both of them don't convert the strings 'false' and 'true' to 0 and 1 ... not
sure what I am missing. Appreciate any tips. TIA.
"exBK" <exBK@.discussions.microsoft.com> wrote in message
news:09146AA0-F234-45F6-9B71-D4F90FDED3B2@.microsoft.com...
>I am trying to update a row in a table. To my SP, I send an XML string.
> One of the columns I am trying to update is of type "Bit" and the value I
> am
> getting from my app is either "true" or "false".
That should work...
declare @.x varchar(10), @.y bit
set @.x = 'true'
set @.y = case when @.x = 'false' then 0 else 1 end
select @.y
The above results in 1. Are you getting an error?
Bryant