The conversion of the varchar value '359342067417520' overflowed an int column - c#

I am creating a web app in mvc-5 angularjs using SQL Server as a database
At one place i am inserting the details of all the mobile I purchased, I created a user defined type in SQL Server which looks like this
CREATE TYPE [dbo].[TyDetails] AS TABLE
(
[transmid] [varchar](50) NULL,
[modelNumber] [varchar](50) NULL,
[Color] [varchar](50) NULL,
[productType] [varchar](50) NULL,
[emeiNo] [varchar](50) NULL,
[emeiNo2] [varchar](50) NULL,
[Uprice] [float] NULL,
[brandid] [varchar](50) NULL
)
and a read only stored procedure which looks like this
create proc [dbo].[Ins_details]
#tbl_data TyDetails readonly
as
begin
insert into tblTransactionD (TransactionMId, modelnumber, color, producttype, brandid, emeino, emeino2, price)
select *
from #tbl_data
end
Now the main table here is named as tblTransactionD which looks like this
CREATE TABLE [dbo].[tblTransactionD]
(
[TransactionDId] [int] IDENTITY(1,1) NOT NULL,
[TransactionMId] [varchar](100) NULL,
[ProductName] [varchar](50) NULL,
[ModelNumber] [varchar](50) NULL,
[Color] [varchar](50) NULL,
[ProductType] [varchar](50) NULL,
[BrandId] [int] NULL,
[EmeiNo] [varchar](50) NULL,
[EmeiNo2] [varchar](50) NULL,
[Qty] [int] NULL,
[Price] [float] NULL,
[ProductTax] [decimal](18, 2) NULL,
CONSTRAINT [PK_tblTransactionD]
PRIMARY KEY CLUSTERED ([TransactionDId] ASC)
) ON [PRIMARY]
I am passing the data through Data table and TYPE into my database
I am passing 359342067417520 in dr["emeiNo"] = em1[id].ToString(); here
here is my code of mvc
DataTable dt = new DataTable();
dt.Columns.Add("transmid");//
dt.Columns.Add("modelNumber");//
dt.Columns.Add("color");//
dt.Columns.Add("productType");//
dt.Columns.Add("emeiNo");//
dt.Columns.Add("emeiNo2");//
dt.Columns.Add("Uprice");//
dt.Columns.Add("brandid");
for (int id = 0; id < ps.Modelnumber.Split(',').Length; id++)
{
string[] mod = ps.Modelnumber.Split(',');
string[] col = ps.Color.Split(',');
string[] typ = ps.phoneType.Split(',');
string[] em1 = ps.emei.Split(',');
string[] em2 = ps.emei2.Split(',');
string[] pri = ps.Uprice.Split(',');
string[] act = ps.onetwo.Split(',');
DataRow dr = dt.NewRow();
dr["modelNumber"] = mod[id].ToString();
dr["color"] = col[id].ToString();
dr["productType"] = typ[id].ToString();
dr["emeiNo"] = em1[id].ToString();
dr["emeiNo2"] = em2[id].ToString();
dr["Uprice"] = Convert.ToDouble(pri[id].ToString());
dr["transmid"] = getgu.ToString();
dr["brandid"] = ps.brandid.ToString();
dt.Rows.Add(dr);
}
SqlCommand cm = new SqlCommand("Ins_details");
cm.ExecuteNonQuery();
but on my execution line I am getting the error
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: The conversion of the varchar value '359342067417520' overflowed an int column.

In short, you are inserting emeino which is string into brandid column which is int. Check the order of your columns in INSERT command in stored procedure. Last four columns in table type are not the same order as you wrote in procedure.
You should change SELECT * from #tbl_data to actually write all columns in same order you made for INSERT
insert into tblTransactionD (TransactionMId, modelnumber, color, producttype, brandid, emeino, emeino2, price)
select transmid, modelnumber, color, producttype, brandid, emeino, emeino2, price
from #tbl_data
Also, brandid column is INT in Database, but VARCHAR(50) in table type and string in C#. Fix it to be consistent through all layers.

Related

Dapper ExecuteAsync get a SQLException: Column name or number of supplied values does not match table definition

I used Dapper ExecuteAsync method to execute a SQL query with params.
insertedId =await connection.ExecuteAsync(query,params, transaction);
But this error occurs:
"Column name or number of supplied values does not match table
definition."
The Good table definition:
[Id] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](50) NULL,
[Title] [nvarchar](200) NOT NULL,
[GoodEnumId] [int] NOT NULL,
[Date] [datetime] NOT NULL,
[IsActive] [bit] NOT NULL,
[IsDeleted] [bit] NOT NULL,
And the PaperDetail table definition:
[Id] [int] IDENTITY(1,1) NOT NULL,
[GoodId] [int] NOT NULL,
[Length] [float] NULL,
[Width] [float] NULL,
[Grammage] [float] NULL,
[Date] [datetime] NOT NULL,
[IsActive] [bit] NOT NULL,
[IsDeleted] [bit] NOT NULL,
This is the query:
declare #Good1Scalar int
create table #Good1 (Id int)
insert into [Good] (Code, Title, GoodEnumId, Date, IsActive, IsDeleted)
output inserted.Id into #Good1
values (#Param2, #Param3, #Param4, #Param5, #Param6, #Param7)
SELECT #Good1Scalar = id from #Good1
drop table #Good1
insert into [PaperDetail](GoodId, Length, Width, Grammage, Date, IsActive, IsDeleted)
values (#Good1Scalar, #Param8, #Param9, #Param10, #Param11, #Param12, #Param13)
And this is my params value and DbType object (of DynamicParameters type):
What's wrong?
Update:
Using SQL Server Profiler I get the final code and run it on the
SQL server management studio directly. The query has no error. So surely this error message is misleading and the problem is somewhere else.
For testing, I remove the transaction and the error disappeared. So
I noticed that the problem is from the transaction. That's why I
reviewed the previous method that takes this transaction (calling the QueryMultiple in one method).
I replaced the dapper QueryMultiple with a DataAdapter Fill method. and finally, the error disappeared.
It's still unclear from the question what is the type of param variable passed to Dapper's ExecuteAsync call. The preferred way of passing parameters is through DynamicParameters bag.
Here is the code that works with your table definitions and the query.
DynamicParameters parameters = new DynamicParameters();
parameters.Add("Param2", "TheCode");
parameters.Add("Param3", "TheTitle");
parameters.Add("Param4", 4);
parameters.Add("Param5", "2018-01-28");
parameters.Add("Param6", true);
parameters.Add("Param7", false);
parameters.Add("Param8", 300);
parameters.Add("Param9", 30);
parameters.Add("Param10", 3);
parameters.Add("Param11", "2018-01-28");
parameters.Add("Param12", true);
parameters.Add("Param13", true);
var insertedId = await connection.ExecuteAsync(query, parameters, transaction);
Give it a try, it should work.

Unable to retrieve specific users foreign key, then output that foreign key row into data grid

I have a users table in my database which has a foreign key for Packages (PackageId), I want a query in which I can retrieve the specific package details for that one user.
So in theory I need to retrieve that users PackageId from the table then output that particular package into my Data grid. Another issue is that I need to verify which user is logged into the application as well to specify which users package details will be output in the grid.
Here is my working log in query which only takes email as verification.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
try
{
con.Open();
string query = "SELECT COUNT(1) from AspNetUsers WHERE Email=#Email";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Email", txtUsername.Text);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count == 1)
{
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
this.Close();
}
else
{
MessageBox.Show("Incorrect Login Information");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Here is my users table Code:
CREATE TABLE [dbo].[AspNetUsers] (
[Id] NVARCHAR (450) NOT NULL,
[APIKey] UNIQUEIDENTIFIER NULL,
[AccessFailedCount] INT NOT NULL,
[AccountType] NVARCHAR (MAX) NULL,
[ConcurrencyStamp] NVARCHAR (MAX) NULL,
[Email] NVARCHAR (256) NULL,
[EmailConfirmed] BIT NOT NULL,
[FirstName] NVARCHAR (MAX) NULL,
[LastName] NVARCHAR (MAX) NULL,
[Locations] INT NOT NULL,
[LockoutEnabled] BIT NOT NULL,
[LockoutEnd] DATETIMEOFFSET (7) NULL,
[NormalizedEmail] NVARCHAR (256) NULL,
[NormalizedUserName] NVARCHAR (256) NULL,
[PackageId] INT NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[PeriodOrderQty] INT NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT NOT NULL,
[Qualifications] INT NOT NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[TotalOrderQty] INT NULL,
[TwoFactorEnabled] BIT NOT NULL,
[UserName] NVARCHAR (256) NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_AspNetUsers_Packages_PackageId] FOREIGN KEY ([PackageId]) REFERENCES [dbo].[Packages] ([Id])
);
GO
CREATE NONCLUSTERED INDEX [EmailIndex]
ON [dbo].[AspNetUsers]([NormalizedEmail] ASC);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([NormalizedUserName] ASC) WHERE ([NormalizedUserName] IS NOT NULL);
GO
CREATE NONCLUSTERED INDEX [IX_AspNetUsers_PackageId]
ON [dbo].[AspNetUsers]([PackageId] ASC);
Here is my packages code:
CREATE TABLE [dbo].[Packages] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Cost] DECIMAL (18, 2) NOT NULL,
[OrderLimit] INT NOT NULL,
[PackageName] NVARCHAR (MAX) NULL,
[ResetInterval] INT NOT NULL,
[ResetIntervalType] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_Packages] PRIMARY KEY CLUSTERED ([Id] ASC)
);
The only connection right now is that User01 in the users table is connected to packageId = "1".
This query worked and output the correct package.
"SELECT p.* FROM AspNetUsers as u JOIN packages as p ON u.package_id = p.id WHERE Email = #Email";

my tableadapter are generating datetime2 fields as string

Im using tableAdapters to insert values to a table.
Heres my table aaTest
CREATE TABLE [dbo].[aaTest](
[id] [int] IDENTITY(1,1) NOT NULL,
[INVOICEDATE] [datetime2](0) NULL,
[CHARGEDATE] [datetime2](0) NULL,
[EZPASS] [varchar](50) NULL,
[PLAZA] [varchar](10) NULL,
[PLAZA2] [varchar](10) NULL,
[PDATE] [datetime2](0) NULL,
[PTIME] [varchar](9) NULL,
[PAMOUNT] [decimal](18, 2) NULL,
[PBALANCE] [decimal](18, 2) NULL,
[ACTION] [varchar](10) NULL
) ON [PRIMARY]
in my dataset, my initial fill command is select * from aatest, and ive created an insert query
INSERT INTO [aatest] ([INVOICEDATE], [CHARGEDATE], [EZPASS], [PLAZA], [PLAZA2], [PDATE], [PTIME], [PAMOUNT], [PBALANCE], [ACTION])
VALUES (#INVOICEDATE, #CHARGEDATE, #EZPASS, #PLAZA, #PLAZA2, #PDATE, #PTIME, #PAMOUNT, #PBALANCE, #ACTION)
now under my dataset designer, my query is being declared as such
public virtual int InsertQuery(string INVOICEDATE, string CHARGEDATE, string EZPASS, string PLAZA, string PLAZA2, string PDATE, string PTIME, global::System.Nullable<decimal> PAMOUNT, global::System.Nullable<decimal> PBALANCE, string ACTION)
the problem im having is, INVOICEDATE, CHARGEDATE and PDATE are being generated as strings when they are in fact datetime2. this causes the exception
The best overloaded method match for (mydataset) has some invalid arguments.
changing it to datetime worked temporary, but after a while they regenerated back to strings.
You need to change [datetime2] to just [datetime], that should fix your issue.

Cannot convert datatype nvarchar to numeric

I import data from from an Excel file into a SQL Server database with the following query. The Excel file has all values as string types (' before every cells).
I get this error when I import it."Cannot convert datatype nvarchar to numeric"
If I remove the two columns SalePrice and Price2 from importing, then the import is successful.
The datatypes of my table is
CREATE TYPE [dbo].[InventoryType] AS TABLE
(
[LocalSKU] [varchar](200) NOT NULL,
[ItemName] [varchar](200) NULL,
[QOH] [int] NULL,
[Price] [decimal](19, 4) NULL,
[Discontinued] [bit] NULL,
[Barcode] [varchar](25) NULL,
[Integer2] [int] NULL,
[Integer3] [int] NULL,
[SalePrice] [decimal](19, 4) NULL,
[SaleOn] [bit] NULL,
[Price2] [decimal](19, 4) NULL
)
GO
The query I am using is:
SqlCommand sqlcmd = new SqlCommand
(#"MERGE Inventory AS target
USING (SELECT
LocalSKU, ItemName, QOH, Price, Discontinued,
Barcode, Integer2, Integer3, SalePrice, SaleOn, Price2
FROM #source) AS Source ON (Source.LocalSKU = target.LocalSKU)
WHEN MATCHED THEN
UPDATE
SET ItemName = source.ItemName,
Price = source.Price,
Discontinued = source.Discontinued,
Barcode = source.Barcode,
Integer2 = source.Integer2,
Integer3 = source.QOH,
SalePrice = source.SalePrice,
SaleOn = source.SaleOn,
Price2 = source.Price2;", sqlconn);
SqlParameter param;
param = sqlcmd.Parameters.AddWithValue("#source", dr);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.InventoryType";
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
One thing to keep in mind is that you may have some invalid data in the given column that's throwing the error(s). For example if you have a Numeric column and have letters or inproperly formatted numeric values, this error will be thrown. Check for values in your cells that aren't correct first. This includes trailing or leading spaces as well.

Comment Count on Entry Table (SQL Query)

It may be a simple/specific question but I really need help on that. I have two tables: Entry and Comment in a SQL Server database. I want to show comment count in entry table. And of course comment count will increase when a comment is added. Two tables are connected like this:
Comment.EntryId = Entry.Id
Entry table:
CREATE TABLE [dbo].[Entry] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Subject] NVARCHAR (MAX) NOT NULL,
[Content] NVARCHAR (MAX) NOT NULL,
[Type] NVARCHAR (50) NOT NULL,
[SenderId] NVARCHAR (50) NOT NULL,
[Date] DATE NOT NULL,
[Department] NVARCHAR (50) NULL,
[Faculty] NVARCHAR (50) NULL,
[ViewCount] INT DEFAULT ((0)) NOT NULL,
[SupportCount] INT DEFAULT ((0)) NOT NULL,
[CommentCount] INT DEFAULT ((0)) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Comment table:
CREATE TABLE [dbo].[Comment] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[EntryId] INT NOT NULL,
[SenderId] NVARCHAR (50) NOT NULL,
[Date] DATETIME NOT NULL,
[Content] NVARCHAR (MAX) NOT NULL,
[SupportCount] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
I am showing the entries in a gridview in codebehind (c#). The question is this, what should I write as a query to do this most efficiently? Thanks for help.
Try this:
select e.Id,e.date,count(*) as NumComments
from Entry e
join comment c on c.entryId=e.id
group by e.id,e.date
If there might be no comments, try the following
select e.Id,e.date,count(c.entryId) as NumComments
from Entry e
left join comment c on c.entryId=e.id
group by e.id,e.date
You can use left join for that purpose. Kindly me more specific with what fields you want in gridview
And why do you want commentcount in table (most tables have that 1-many relation and we didn't use that). If you keep that in table you have to update entry table every time when comment is made.

Categories

Resources