I am stuck in this condition unable to insert into the table tbl_customer its giving error :
Arithmetic overflow error converting expression to data type int.
The statement has been terminated.
here is my table structure:
create table tbl_customer(
id int identity primary key,
cust_name varchar(50) NOT NULL,
filecode varchar(20) NOT NULL,
cust_mobile int,
cust_cnic varchar(50) NOT NULL,
cust_phone int,
cust_address varchar(200)
)
and here is the code i use to insert:
insert into tbl_customer values('Jonah Gordian','LHR001',03451119182,'11-22112-122',1212121212,'abc street 12')
and I used this code in c# to try inserting:
connclass.insert("insert into tbl_customer(cust_name,filecode,cust_mobile,cust_cnic,cust_phone,cust_address) VALUES('" + txtname.Text + "','" + txtfilecode.Text + "','" + int.Parse(txtmob.Text) + "','" + txtcnic.Text + "','" + int.Parse(txtphone.Text) + "','" + txtaddress.Text + "')");
create table tbl_customer(
id int identity primary key,
cust_name varchar(50) NOT NULL,
filecode varchar(20) NOT NULL,
cust_mobile varchar(20),
cust_cnic varchar(50) NOT NULL,
cust_phone varchar(20),
cust_address varchar(200)
)
insert into tbl_customer
(cust_name, filecode, cust_mobile, cust_cnic, cust_phone, cust_address )
values
('Jonah Gordian','LHR001','03451119182','11-22112-122','1212121212','abc street 12');
And also C# code is open to SQL injection attack, use parameters instead. ie:
string sql = #"insert into tbl_customer
(cust_name,filecode,cust_mobile,cust_cnic,cust_phone,cust_address)
VALUES
(#cust_name,#filecode,#cust_mobile,#cust_cnic,#cust_phone,#cust_address)";
using (SqlConnection con = new SqlConnection(#"server=.\SQLExpress;database=yourDbName;Trusted_Connection=yes"))
{
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#cust_name", txtname.Text);
cmd.Parameters.AddWithValue("#filecode", txtfilecode.Text);
cmd.Parameters.AddWithValue("#cust_mobile", txtmob.Text);
cmd.Parameters.AddWithValue("#cust_cnic", txtcnic.Text);
cmd.Parameters.AddWithValue("#cust_phone", txtphone.Text);
cmd.Parameters.AddWithValue("#cust_address", txtaddress.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You define cust_mobile as int, but try to insert 03451119182, which is clearly over the limit of 2147483647.
Change to bigint or store as a VarChar (including the leading zero).
Try like this,
CREATE TABLE tbl_customer (
id INT identity PRIMARY KEY
,cust_name VARCHAR(50) NOT NULL
,filecode VARCHAR(20) NOT NULL
,cust_mobile BIGINT --or Varchar(20)
,cust_cnic VARCHAR(50) NOT NULL
,cust_phone INT
,cust_address VARCHAR(200)
)
INSERT INTO tbl_customer
VALUES (
'Jonah Gordian'
,'LHR001'
,03451119182
,'11-22112-122'
,1212121212
,'abc street 12'
)
You have exceeded the int datatype limit. Change the datatype from int to either bigint or Varchar to resolve the issue.
Note: If you need leading Zeros then you can choose Varchar otherwise you can make use of BigInt.
You exceeded the limit of the int try with bigint
this value 3451119182
see in this link the limits
https://msdn.microsoft.com/pt-br/library/ms187745(v=sql.120).aspx
Related
I am working with C# and I want to insert some values to my SQL Server database, here is my data base definition:
CREATE TABLE [dbo].[Users]
(
[Id] INT NOT NULL IDENTITY (1,1) PRIMARY KEY DEFAULT 1000,
[FullName] VARCHAR(50) NULL,
[Pseudo] VARCHAR(50) NULL,
[Mail] VARCHAR(50) NULL,
[Password] VARCHAR(50) NULL,
[Organism] VARCHAR(50) NULL,
[RegistredAt] DATETIME NULL,
[Confirmed] INT NULL
)
and this how I am trying to insert the values to the database using C#:
SqlCommand command = new SqlCommand("INSERT INTO Users VALUES(#FullName, #Pseudo, #Mail, #Password, #Organism, #RegistredAt, #Confirmed)", con);
command.Parameters.AddWithValue("#FullName", FullName);
command.Parameters.AddWithValue("#Pseudo", Pseudo);
command.Parameters.AddWithValue("#Mail", Mail);
command.Parameters.AddWithValue("#Password", Password);
command.Parameters.AddWithValue("#Organism", Organism);
command.Parameters.AddWithValue("#RegistredAt", DateTime.Now);
command.Parameters.AddWithValue("#Confirmed", Confirmed);
con.Open();
int i = command.ExecuteNonQuery();
con.Close();
When I execute the code, the instruction command.ExecuteNonQuery(); returns an exception:
Column name or number of supplied values does not match table definition
Where is the error?
You might need to supply the column names in your query:
INSERT INTO Users (FullName, Pseudo, Mail, Password, Organism, RegistredAt, Confirmed)
VALUES (#FullName, #Pseudo, #Mail, #Password, #Organism, #RegistredAt, #Confirmed)
If you don't supply the column names, it assumes you want to use all columns, including the ID field. That's the reason for the error -- you're supplying 7 values for a table with 8 columns. Since you are using a subset, you need to specify them.
Also, I'm not sure if you are at a stage where it can be fixed, but you have a typo in "RegistredAt" -- it should be "RegisteredAt".
con1.Open();
cmd = new SqlCommand("create table [dbo.][" + textBox2.Text + "](sno int primary key identity(1,1),[Week] [int] not null ,Date nvarchar(30) not null,Time nvarchar(30) not null,Monday_1st_half nvarchar(20),Monday_2nd_half nvarchar(20),Tuesday_1st_half nvarchar(20),Tuesday_2nd_half nvarchar(20),Wednesday_1st_half nvarchar(20),Wednesday_2nd_half nvarchar(20),Thursday_1st_half nvarchar(20),Thursday_2nd_half nvarchar(20),Friday_1st_half nvarchar(20),Friday_2nd_half nvarchar(20),Saturday_1st_half nvarchar(20),Saturday_2nd_half nvarchar(20),Sunday_1st_half nvarchar(20),Sunday_2nd_half nvarchar(20))", con1);
cmd.ExecuteNonQuery();
con1.Close();
This query works if i give the table a hard coded name instead of the textbox.text value, a table is created.
But when i use this code it creates a table with the name 'dbo.'.
If i delete the "[dbo.]" from the query, it gives an error saying 'object is missing'. can someone help me out?.
Here's a better way to do this. First create the following stored procedure:
CREATE PROC dbo.MakeUserTable(#Tablename as SYSNAME) As
DECLARE #CleanName As SYSNAME;
SET #CleanName = QUOTENAME(#Tablename, '[');
DECLARE #sql As NVARCHAR(MAX);
SELECT #sql = 'create table [dbo].' + #CleanName + '(sno int primary key identity(1,1),[Week] [int] not null ,Date nvarchar(30) not null,Time nvarchar(30) not null,Monday_1st_half nvarchar(20),Monday_2nd_half nvarchar(20),Tuesday_1st_half nvarchar(20),Tuesday_2nd_half nvarchar(20),Wednesday_1st_half nvarchar(20),Wednesday_2nd_half nvarchar(20),Thursday_1st_half nvarchar(20),Thursday_2nd_half nvarchar(20),Friday_1st_half nvarchar(20),Friday_2nd_half nvarchar(20),Saturday_1st_half nvarchar(20),Saturday_2nd_half nvarchar(20),Sunday_1st_half nvarchar(20),Sunday_2nd_half nvarchar(20));'
PRINT 'Executing "'+#sql+'"';
EXEC(#sql);
Now change your client code to execute this instead, passing in the tablename as a parameter.
I cannot 100% guarantee that this is immune to SQL Injection attacks, but if you have to accept a tablename from a user, this is about as safe as you can get.
I would like to insert a record into table RDV .
The query of creation RDV Table:
CREATE TABLE [dbo].[RDV] (
[idRdv] INT NOT NULL,
[objet] NVARCHAR (50) NULL,
[objectif] NVARCHAR (50) NULL,
[DateRdv] DATETIME NULL,
[commentaire] NVARCHAR (50) NULL,
[archive] NVARCHAR (50) NULL,
[idClient] INT NULL,
[idUser] INT NULL,
[idResultat] INT NULL,
CONSTRAINT [PK_RDV] PRIMARY KEY CLUSTERED ([idRdv] ASC),
FOREIGN KEY ([idClient]) REFERENCES [dbo].[Client] ([idClient]),
FOREIGN KEY ([idUser]) REFERENCES [dbo].[User] ([idUser]),
FOREIGN KEY ([idResultat]) REFERENCES [dbo].[Resultat] ([idResultat])
There is here my code :
private void btnAdd_Click(object sender, EventArgs e)
{
SqlDataAdapter sda = new SqlDataAdapter("Insert into RDV (objet,objectif,DateRdv,commentaire,idClient)Select'" + textBox1.Text + "','" + textBox2.Text + "','" + dateTimePicker1.Text.ToString() + "','" + textBox4.Text + "',idClient from RDV where Client.idClient=RDV.idClient and idClient='"+comboBox2.SelectedValue+"'", con);
sda.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("Le RDV a été ajouté avec succés !");
}
The Error was: The multi-part identifier " Client.idClient " can not be bound.
My syntax query it's wrong ??? if yes , how should I correct it .
Thanks in advance.
Well as the error says there is no reference to the Client table in your query, so it won't find the identifier Client.idClient. Either use a join or put Client in your From.
One problem is Insert syntax.
Insert into RDV ("table columns")
Values ("values")
Example: (http://www.w3schools.com/sql/sql_insert.asp)
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
Hy,
I have created the following 3 tables for a database:
CREATE TABLE [dbo].[Buyer] (
[Buyer_Id] INT IDENTITY (1, 1) NOT NULL,
[Last_Name] NVARCHAR (50) NOT NULL,
[First_Name] NVARCHAR (50) NOT NULL,
[Social_No] NVARCHAR (50) NOT NULL,
[Phone] NVARCHAR (50) NOT NULL,
[User_Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Buyer_Id] ASC),
CONSTRAINT [FK_User_Id] FOREIGN KEY ([User_Id]) REFERENCES [dbo].[User] ([User_Id])
);
CREATE TABLE [dbo].[Type] (
[Type_Id] INT IDENTITY (1, 1) NOT NULL,
[Type_Name] NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Type_Id] ASC)
);
CREATE TABLE [dbo].[User] (
[User_Id] INT IDENTITY (1, 1) NOT NULL,
[User_Name] NCHAR (10) NOT NULL,
[Pass] NVARCHAR (50) NOT NULL,
[Type_Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([User_Id] ASC),
CONSTRAINT [FK__Type_Id] FOREIGN KEY ([Type_Id]) REFERENCES [dbo].[Type] ([Type_Id])
);
and I have the following stored procedure
CREATE PROCEDURE [dbo].[InsertCustomer]
#Buyer_Id int output,
#Last_Name varchar(50),
#First_Name varchar(50),
#Social_No varchar(50),
#Phone varchar(50),
#User_Id int output,
#User_Name nchar(10),
#Pass varchar(50),
#Type_id int output,
#Type_Name nchar(10)
AS
BEGIN
SET NOCOUNT ON;
insert into Buyer(Last_Name,First_Name,Social_No,Phone)
values (#Last_Name,#First_Name,#Social_No,#Phone)
set #Buyer_Id = SCOPE_IDENTITY();
insert into [User](User_Name,Pass)
values(#User_Name,#Pass)
set #User_Id = SCOPE_IDENTITY();
insert into [Type](Type_Name)
values (#Type_Name)
set #Type_id = SCOPE_IDENTITY();
RETURN 0
END
and the C# code:
SqlCommand cmd = new SqlCommand("InsertCustomer", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramLastName = new SqlParameter("#Last_Name", customer.Last_Name);
SqlParameter paramFirstName = new SqlParameter("#First_Name", customer.First_Name);
SqlParameter paramSocialNo = new SqlParameter("#Social_No", customer.Social_No);
SqlParameter paramPhone = new SqlParameter("#Phone", customer.Phone_No);
SqlParameter paramUserName = new SqlParameter("User_name", user.User_Name);
SqlParameter paramPass = new SqlParameter("#Pass", user.Pass);
SqlParameter paramTypeName = new SqlParameter("#Type_Name", type.Type_Name);
SqlParameter paramBuyerId = new SqlParameter("#Buyer_Id", SqlDbType.Int);
paramBuyerId.Direction = ParameterDirection.Output;
SqlParameter paramUserId = new SqlParameter("#User_Id", SqlDbType.Int);
paramUserId.Direction = ParameterDirection.Output;
SqlParameter paramTypeId = new SqlParameter("#Type_Id", SqlDbType.Int);
paramTypeId.Direction = ParameterDirection.Output;
cmd.Parameters.Add(paramLastName);
cmd.Parameters.Add(paramFirstName);
cmd.Parameters.Add(paramSocialNo);
cmd.Parameters.Add(paramPhone);
cmd.Parameters.Add(paramUserName);
cmd.Parameters.Add(paramPass);
cmd.Parameters.Add(paramTypeName);
cmd.Parameters.Add(paramBuyerId);
cmd.Parameters.Add(paramUserId);
cmd.Parameters.Add(paramTypeId);
conn.Open();
cmd.ExecuteNonQuery();
customer.Buyer_Id = (int)paramBuyerId.Value;
type.Type_Id = (int)paramTypeId.Value;
user.User_Id = (int)paramUserId.Value;
But after I insert data into the form that uses the above code I am getting the following error:
Cannot insert the value NULL into column 'User_Id' ....
PLATFORM.MDF.dbo.Buyer'; column does not allow nulls. INSERT fails.
Cannot insert the value NULL into column 'Type_Id', table ...
PLATFORM.MDF.dbo.User'; column does not allow nulls. INSERT fails.
Please help me,
Sincerely,
You should change insert order. First of all you should insert new type
insert into [Type](Type_Name)
values (#Type_Name)
set #Type_id = SCOPE_IDENTITY();
After that you should insert new user (use #type_id for that)
insert into [User](User_Name,Pass,Type_id)
values(#User_Name,#Pass,#Type_id)
set #User_Id = SCOPE_IDENTITY();
Filnaly, use #User_Id to insert Buyer. In turn use #User_Id
insert into Buyer(Last_Name,First_Name,Social_No,Phone,User_id)
values (#Last_Name,#First_Name,#Social_No,#Phone,#User_Id)
set #Buyer_Id = SCOPE_IDENTITY();
You have errors in your stored procedure, since you are not specifying values for the User_Id or Type_Id columns but those columns don't allow null values.
You should reverse the order of the inserts and use the generated identity values in the following ones, like so:
insert into [Type](Type_Name)
values (#Type_Name)
set #Type_id = SCOPE_IDENTITY();
insert into [User](User_Name,Pass,TypeId)
values(#User_Name,#Pass,#Type_id)
set #User_Id = SCOPE_IDENTITY();
insert into Buyer(Last_Name,First_Name,Social_No,Phone,User_Id)
values (#Last_Name,#First_Name,#Social_No,#Phone,#User_Id)
set #Buyer_Id = SCOPE_IDENTITY();
I've seen this:
How can you dynamically select a table with entity framework 4.x?
However I cannot use a base class in my situation. I am looking to create a user group and week sensitive table for auditing, so I cannot know what these will be called prior to them being created at runtime.
So if I login first week of the year, it would be:
Group1_01_2014
Is this possible? I've tried to simply change the database name at creation, but I get the standard exception about database migrations.
Thanks.
Edit: Before someone says splitting the database is silly, know that I'm auditing ALOT. The idea is to be able to audit most transactions, store them as long as needed, without severely affecting performance.
Edit2: That said if someone has a better solution I'm all ears.
Solution
Ended up using a stored procedure:.
CREATE FUNCTION GetAuditTableName
(
#db_code CHAR (4)
)
RETURNS CHAR (12)
BEGIN
DECLARE #wkNo CHAR (2)
DECLARE #year CHAR (4)
SELECT #wkNo = REPLACE(STR(DATEPART(WEEK, GETDATE()), 2), SPACE(1), '0')
SELECT #year = STR(DATEPART(YEAR, GETDATE()), 4)
RETURN #db_code + '_' + #year + '_' + #wkNo
END
GO
CREATE PROCEDURE [dbo].[Audit_Insert]
#audi_id_first NVARCHAR (20),
#audi_id_second NVARCHAR (20),
#audi_by NVARCHAR (100),
#audi_on DATETIME,
#audi_details XML,
#tabn_code CHAR (4),
#audt_id INT,
#audi_db_code CHAR (4)
AS
BEGIN
DECLARE #tableName CHAR (12)
SET #tableName = [dbo].GetAuditTableName(#audi_db_code)
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=#tableName and xtype='U')
BEGIN
DECLARE #createSql NVARCHAR(MAX);
SELECT #createSql = 'CREATE TABLE [dbo].' + QUOTENAME(#tableName) + ' (
[audi_id] INT IDENTITY (1, 1) NOT NULL,
[audi_id_first] NVARCHAR (20) NULL,
[audi_id_second] NVARCHAR (20) NULL,
[audi_by] NVARCHAR (100) NOT NULL,
[audi_on] DATETIME NOT NULL,
[audi_details] XML NULL,
[tabn_code] CHAR (4) NULL,
[audt_id] INT NOT NULL,
CONSTRAINT [PK_dbo.' + #tableName + '] PRIMARY KEY CLUSTERED ([audi_id] ASC),
CONSTRAINT [FK_dbo.' + #tableName + '_dbo.tabn_table_name_tabn_code] FOREIGN KEY ([tabn_code]) REFERENCES [dbo].[tabn_table_name] ([tabn_code]),
CONSTRAINT [FK_dbo.' + #tableName + '_dbo.audt_audit_type_audt_id] FOREIGN KEY ([audt_id]) REFERENCES [dbo].[audt_audit_type] ([audt_id])
)'
EXEC sp_executesql #createSql
END
DECLARE #insertSql NVARCHAR(MAX);
SELECT #insertSql = N'INSERT [dbo].' + QUOTENAME(#tableName) + ' ([audi_id_first], [audi_id_second], [audi_by], [audi_on], [audi_details], [tabn_code], [audt_id])
VALUES (#audi_id_first, #audi_id_second, #audi_by, #audi_on, #audi_details, #tabn_code, #audt_id)'
EXEC sp_executesql #insertSql, N'#audi_id_first NVARCHAR (20), #audi_id_second NVARCHAR (20), #audi_by NVARCHAR (100), #audi_on DATETIME, #audi_details XML, #tabn_code CHAR (4), #audt_id INT', #audi_id_first, #audi_id_second, #audi_by, #audi_on, #audi_details, #tabn_code, #audt_id
DECLARE #idSql NVARCHAR(MAX);
SELECT #idSql = 'DECLARE #audi_id INT
SELECT #audi_id = [audi_id]
FROM [dbo].' + QUOTENAME(#tableName) + '
WHERE ##ROWCOUNT > 0 AND [audi_id] = scope_identity()
SELECT t0.[audi_id]
FROM [dbo].' + QUOTENAME(#tableName) + ' AS t0
WHERE ##ROWCOUNT > 0 AND t0.[audi_id] = #audi_id'
EXEC sp_executesql #idSql
END
GO
then calling this from C#:
public void AddRecord(Audit record)
{
var Id1 = new SqlParameter("#audi_id_first", SqlDbType.NVarChar);
Id1.Value = (object)record.Id1 ?? System.DBNull.Value;
var Id2 = new SqlParameter("#audi_id_second", SqlDbType.NVarChar);
Id2.Value = (object)record.Id2 ?? System.DBNull.Value;
var UserName = new SqlParameter("#audi_by", SqlDbType.NVarChar);
UserName.Value = record.UserName;
var Stamp = new SqlParameter("#audi_on", SqlDbType.DateTime);
Stamp.Value = record.Stamp;
var Details = new SqlParameter("#audi_details", SqlDbType.Xml);
Details.Value = (object)record.Details ?? System.DBNull.Value;
var TableCode = new SqlParameter("#tabn_code", SqlDbType.Char);
TableCode.Value = record.TableCode;
var TypeId = new SqlParameter("#audt_id", SqlDbType.Int);
TypeId.Value = record.TypeId;
var DatabaseCode = new SqlParameter("#audi_db_code", SqlDbType.Char);
DatabaseCode.Value = CallingPrefix;
this.Database.ExecuteSqlCommand("EXEC Audit_Insert #audi_id_first, #audi_id_second, #audi_by, #audi_on, #audi_details, #tabn_code, #audt_id, #audi_db_code",
Id1, Id2, UserName, Stamp, Details, TableCode, TypeId, DatabaseCode);
}
My next struggle is getting it to work with IQueryable OData requests.
Solution 2
CREATE PROCEDURE [dbo].[CreateAuditTableIfNoneExists]
#tableName CHAR (12)
AS
BEGIN
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=#tableName and xtype='U')
BEGIN
DECLARE #createSql NVARCHAR(MAX);
SELECT #createSql = 'CREATE TABLE [dbo].' + QUOTENAME(#tableName) + ' (
[audi_id] INT IDENTITY (1, 1) NOT NULL,
[audi_id_first] NVARCHAR (20) NULL,
[audi_id_second] NVARCHAR (20) NULL,
[audi_by] NVARCHAR (100) NOT NULL,
[audi_on] DATETIME NOT NULL,
[audi_details] XML NULL,
[tabn_code] CHAR (4) NULL,
[audt_id] INT NOT NULL,
CONSTRAINT [PK_dbo.' + #tableName + '] PRIMARY KEY CLUSTERED ([audi_id] ASC),
CONSTRAINT [FK_dbo.' + #tableName + '_dbo.tabn_table_name_tabn_code] FOREIGN KEY ([tabn_code]) REFERENCES [dbo].[tabn_table_name] ([tabn_code]),
CONSTRAINT [FK_dbo.' + #tableName + '_dbo.audt_audit_type_audt_id] FOREIGN KEY ([audt_id]) REFERENCES [dbo].[audt_audit_type] ([audt_id])
)'
EXEC sp_executesql #createSql
END
END
and on database initialisation make sure the table is present:
public class AuditInitialiser : IDatabaseInitializer<AuditContext>
{
public void InitializeDatabase(AuditContext context)
{
if (context.Database.CreateIfNotExists())
{
Seed(context);
}
var tableName = new SqlParameter("#tableName", SqlDbType.Char);
tableName.Value = context.AuditTableName;
context.Database.ExecuteSqlCommand("EXEC CreateAuditTableIfNoneExists #tableName", tableName);
}
However this only works for me because I am using an API, so is stateless and constructs the DbContext every time. This ensures the table is always present. Wouldn't work if I was doing my working out on a stated system.
I'm not a huge fan of stored procedures, but this might be a case where you want to use EF 6's (EF5??)'s ability to bind to stored procs. Then you could pass the table to use as parameter. See if this helps: How to call Stored Procedure in Entity Framework 6 (Code-First)?
(you could also perhaps use EntitySQL to solve this)