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.
Related
I've been struggling to get the defined data table to be accepted as a variable for one of the parameters of the stored procedure.
1st time using user defined tables so I may have made syntax errors
This will be so I can send a data table from a c# program instead of individually inserting each row.
Stored Procedure
CREATE PROCEDURE [dbo].[Upload_AddBulkProducts]
#uploadedTable CSV_ADDProducts readonly
AS
INSERT INTO [dbo].[Products]
SELECT * FROM #uploadedTable
GO
Error = undefined variable
The error i get when trying to create the stored procedure
User Defined Table
CREATE TYPE [dbo].[CSV_ADDProducts] AS TABLE(
[Product Item] [nvarchar](50) NULL,
[Product SKU] [bigint] NULL,
[Product Name] [nvarchar](max) NULL,
[Product Active] [nchar](10) NULL,
[Product Selling Price] [money] NULL,
[Product Description] [nvarchar](max) NULL,
[Product Purchase Description] [nvarchar](max) NULL,
[Product VAT Code ID] [bigint] NOT NULL,
[Product Last Update] [datetime] NULL
)
GO
In the context of T-SQL your code is valid. The type can be created and the procedure, too.
Then, in the C# code use the following:
DataTable dt = new DataTable();
dt.Columns.Add("Product Item", typeof (string));
//add other columns here
SqlParameter param = new SqlParameter("#uploadedTable", SqlDbType.Structured)
{
TypeName = "dbo.userdefinedtabletype",
Value = dt
};
sqlComm.Parameters.Add(param);
i want to see the data only with the invoice ID i enter so i tried this code to do that
Crystal_Bill cr = new Crystal_Bill();
SqlConnection conect = new SqlConnection("Data Source=DESKTOP-R34C6VV\\SQL;Initial Catalog=Restaurant;Integrated Security=True");
string sql = "Select * from Orders where InvoiceID='"+PrepareBill_txt1.Text+"'";
DataSet dt = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,conect);
adapter.Fill(dt,"Orders");
cr.SetDataSource(dt.Tables["Orders"]);
open.crystalReportViewer1.ReportSource = cr;
Print open = new Print();
open.SHow();
but it did not work i still get all the data in the database is there is a problem in these codes ? can anyone fix it ? thanks
this is my data base
CREATE TABLE [dbo].[Orders] (
[InvoiceID] INT NOT NULL,
[ItemNO] INT NOT NULL,
[Category] VARCHAR (50) NULL,
[ItemName] VARCHAR (50) NULL,
[Price] FLOAT (53) NULL,
[Qty] INT NOT NULL,
[SubTotal] FLOAT (53) NULL,
CONSTRAINT [Orders_FK1] FOREIGN KEY ([InvoiceID]) REFERENCES [dbo].[Invoice] ([InvoiceID])
);
As per your code you are passing invoice ID as a parameter value in your SQl Query, Your invoice ID has INT datatypes and you are trying to pass it with a single quote in your query so that consider invoice id as a varchar value. You can remove a single quote and try once again. that may help you.
i.g:
string sql = "Select * from Orders where InvoiceID="+ PrepareBill_txt1.Text +"";
I'm currently learning to work with databases and SQL. I'm getting an error which I can't seem to resolve. The error I'm getting is stated in the title.
This is my table definition:
CREATE TABLE [dbo].[Filmstbl]
(
[Id] INT NOT NULL IDENTITY,
[FilmTitel] NVARCHAR (50) NULL,
[Duratie] NVARCHAR (50) NULL,
[Genre] NVARCHAR (50) NULL,
[Director] NVARCHAR (50) NULL,
[Acteur] NVARCHAR (50) NULL,
[JaarVanUitgave] NVARCHAR (50) NULL,
[Omschrijving] NVARCHAR (MAX) NULL,
[GastID] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
The query im using looks like this:
public void AddFilms(string titel, string lengte, string genre, string director, string acteur, string jaaruitgave, string omschrijving, int PersoonID)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string query = "INSERT INTO Filmstbl Values (#FilmTitel, #Duratie, #Genre, #Director, #Acteur, #JaarVanUitgave, #Omschrijving, #GastID)";
using (SqlCommand addfilms = new SqlCommand(query, connection))
{
addfilms.Parameters.AddWithValue("#FilmTitel", titel);
addfilms.Parameters.AddWithValue("#Duratie", lengte);
addfilms.Parameters.AddWithValue("#Genre", genre);
addfilms.Parameters.AddWithValue("#Director", director);
addfilms.Parameters.AddWithValue("#Acteur", acteur);
addfilms.Parameters.AddWithValue("#JaarVanUitgave", jaaruitgave);
addfilms.Parameters.AddWithValue("#Omschrijving", omschrijving);
addfilms.Parameters.AddWithValue("#GastID", PersoonID);
addfilms.ExecuteNonQuery();
}
}
}
The datatypes are pretty much always a random string, except the last parameter which is a random int.
private void FilmToevoegenBtn_Click(object sender, EventArgs e)
{
sql.AddFilms(FilmTitelTBox.Text, FilmLengteTBox.Text, FilmGenreTBox.Text, FilmDirectorTBox.Text, FilmActeurTBox.Text, FilmJaarUitgaveTBox.Text, FilmOmschrijvingTBox.Text, gebruiker.GebruikerID);
UpdateListBoxes();
}
I'm adding data to another table the same way without a problem, so i'm wondering why it doesn't work with this one. I hope someone knows the answer. Thank you.
Please re-check table ID field.It should be auto increment with 1. e.g.:
[Id] [int] IDENTITY(1,1)
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.
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.