Trying to insert numeric info in database - mysql

I'm trying to insert a number in a field of my sql database. The table is:
Create table IF NOT EXISTS LJugador(
Fecha date,
vm int,
totalpuntos int,
nom_jugador varchar(80),
FOREIGN KEY (nom_jugador) REFERENCES Jugadores(nombre),
PRIMARY KEY(Fecha, nom_jugador)
)engine=innodb;
The PHP code for insert:
$ljuga_in = "INSERT INTO ljugador VALUE( now(), '{$jugadores[$m][2]}','{$jugadores[$m][3]}', '{$jugadores[$m][1]}' )";
when I do echo of $ljuga_in to see if it is being inserted correctly, I get:
INSERT INTO ljugador VALUE( now(), '4.130.000','92', 'Osman' );
You can see the number is being inserted correctly, but when I make a select query to see the information, VM has 4130 - the last three zeros are not there.
The field is int, but I have tried with numeric and double or float and nothing is working.

Try using DECIMAL(n, p) where n is the overall number of digits and p the number of digits after the comma, so e.g. for DECIMAL(10, 2) the maximum that can be represented would be 99.999.999,99

Related

how to Allow only alpha numeric values in mysql

I have a table
CREATE TABLE table_name
(
EmpId VARCHAR(50),
Name VARCHAR(100)
)
How can I restrict the EmpId column to consist of two letters followed by 3-5 digits? The following are all examples of valid values:
ac236, ak2356, av23695, ak365
I tried using the following check constraint:
ALTER TABLE table_name
ADD CONSTRAINT ck_table_name CHECK (EmpId NOT LIKE'%[^a-zA-Z0-9 ]%')
However, it allows all combinations of letters & digits, such as "23" and "fads":
INSERT INTO table_name
VALUES
('23', 'Test 2'),
('fabs', 'Test 2');
If a value violates the format, I'd like the query to fail and print error message. For example, if 'na23' were inserted as the EmpID, MySQL could say:
Empid should be ab123/ab1234/a12345 format
Initially, I was using MySQL 5.7.11-0ubuntu6-log (which, it turns out, doesn't support CHECK constraints), but have upgraded to MySQL 8.0.17.
Assuming it's MySQL >=8.0.16
check(EmpId regexp '^[a-z]{2}[0-9]{3,5}$')

primary key auto reset increment value

I have a question about creating a primary key for a table using two of its data elements along with an automatically incrementing value.
I have a table that contains
Dataset-a three letter acronym and
DepositDate
I would like to create a primary key for this table that combines dataset and depositDate with an automatically incrementing value.
I can create this column with a value that keeps growing larger, but what I would like is for it to reset with each new day.
For example, on 11/8/2013 for ACA, the first insert for the day would have an identifier of:
ACA-110813-01
the second:
ACA-110813-02
and so on
Then the first insert on 11/9/2013 would be:
ACA0-110913-01
Is this possible in table creation or through any stored procedures or triggers?
I am using SQLServer 2008
Thank you in advance.
A solution I found was to use a stored procedure to insert the data into my table.
I created a column in my target table (ledgers.deposits) called depositNum which is the value I will be incrementing.
CREATE TABLE [Ledgers].[Deposits]
(
[Dataset] [nvarchar](3),
[DepositDate] [date],
[Payer] [nvarchar](100),
[CheckNum] [nvarchar](100),
[CheckAmt] [decimal](18, 2),
[depositNum] [bigint],
[depositId] AS ((((((CONVERT([nvarchar],[Dataset],0)+'-')+ CONVERT([nvarchar],datepart(month,[DepositDate]),0))+CONVERT([nvarchar],datepart(day,[DepositDate]),0))+CONVERT([nvarchar],datepart(year,[DepositDate]),0))+'-')+CONVERT([nvarchar],[depositNum],0))))
I insert data with a stored procedure which will increment the depositNum based on the dataset and the day. Then that value is concatenated into the depositId column which I set as the primary key.
Here is the stored procedure that inserts the data and increments the depositNum.
CREATE PROCEDURE [Ledgers].[insertDeposit]
#dataset nvarchar(3),
#depositDate date,
#payer nvarchar(100),
#checkNum nvarchar(100),
#depositAmt decimal(18,2)
AS
insert into Ledgers.Deposits
values(
#dataset,
#depositDate,
#payer,
#checkNum,
#depositAmt,
(
select ISNULL(max(depositNum+1), 1)
from Ledgers.Deposits
where Dataset=#dataset and DepositDate=#depositDate
))
Hopefully that makes sense.

fixed digits data type in sql

I want user to input only 11 digits , if not, an error should be occured on sql, what type of variable should I use in my sql code.
My current code :
st.executeUpdate("CREATE TABLE User(idUser numeric(11,0) not NULL,uName char(30), uSurname char (30), uAddress varChar(500), primary key(idUser) )");
If you want to make this kind of check on db side in MySQL you can use a trigger
CREATE TRIGGER tg_bi_user
BEFORE INSERT ON user
FOR EACH ROW
SET NEW.idUser = IF(NEW.idUser BETWEEN 10000000000
AND 99999999999, NEW.idUser, NULL);
The trick is to violate NOT NULL when NEW.idUser not in a proper range. If you are on MySQL 5.5 or higher you can also use SIGNAL.
Here is SQLFiddle demo. Try to uncomment the last insert statement and see it won't succeed.
If the variable is numeric, you can use a check constraint:
CREATE TABLE User(idUser numeric(11,0) not NULL,uName char(30), uSurname char (30),
uAddress varChar(500), primary key(idUser),
CHECK(idUser > 9999999999 AND idUser <= 99999999999) )'
Though you'll want to check if the datatype numeric accepts numbers large enough. If not you could to use varchar

Can't Insert Row into Table (Column Count Mismatch)

I've got a script that's creating a table, and then inserting a row afterwards. Here is my SQL code executing to create the table:
CREATE TABLE polls (
id INT NOT NULL UNIQUE AUTO_INCREMENT,
name VARCHAR(255) NOT NULL UNIQUE,
author VARCHAR(255) NOT NULL,
created DATETIME NOT NULL,
expires DATETIME,
PRIMARY KEY(id)
)
And here is where I add a new row:
INSERT INTO polls
VALUES ('TestPoll'),('Billy Bob'),('2013-05-01 04:17:31'),('2013-05-01 04:17:31')
or
INSERT INTO polls
VALUES ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31')
(I get the same error regardless)
I always get this error:
<class '_mysql_exceptions.OperationalError'>, OperationalError(1136, "Column count doesn't match value count at row 1"), <traceback object at 0x7f7bed982560>
Your syntax is wrong, try:
INSERT INTO polls
VALUES ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31')
but if your table structure changes, your code will break, a safer version is:
INSERT INTO polls (name, author, created, expires)
VALUES ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31')
Your INSERT query is not correctly formatted.
INSERT INTO polls (name, author, created, expires)
VALUES ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31');
For more information, visit MySQL Reference Manual for the INSERT statement.
EDIT: It's always a good idea to explicitly type each column name, in case the table structure will change in some foreseeable future.
In mysql you have to pass column name in your insert query.After assigning column name your query will look like
INSERT INTO polls (name,author,created,expires) values ('TestPoll','Billy Bob','2013-05-01 04:17:31','2013-05-01 04:17:31');
Hope it helps.

Output current id of inserted record using OUTPUT in a trigger

I need to do this: On inserted record I need to store Inserted item identity and selected item identity. (Example below)
I'm using after insert trigger (basically I copy one row from one table into another and do some more modifications.
I have a table parameter like this:
DECLARE #Tempequipment TABLE
(Equipment_Id int,
DefaultEquipment_Id INT)
Then I insert into table like this:
INSERT INTO dbo.tblEquipmentType
( Name, EquipmentType_Id)
SELECT name,(SELECT Equiment_Id FROM INSERTED)
FROM dbo.tblDefaultEquipmentType
This works fine!
What I need to do is: I need to insert into #TempEquipment EquipmentTypeId's that were just ineserted (can be more than one) and DefaultEquipmentTypeId's that were just copied.
I was thinking about doing something like:
INSERT INTO dbo.tblEquipmentType
( Name, EquipmentType_Id)
Output EquipmentTypeId, DefaultEquipmentTypeId into #TempEquipment
SELECT name,(SELECT Equipment_Id FROM INSERTED)
FROM dbo.tblDefaultEquipmentType
but of course this is not going to work, since it cannot get values from select statement, and not written correctly.
Any help is appreciated!
UPDATE:
I have an Item. Item can be built on different equipment. Equipment has types (foreign key. And equipmentType has attributes (foreignkey).
So this mean that we have four tables Item->Equipment->EquipmentType->EquipmentAttribute.
I need to store default EquipmentTypes and default EquipmentAtrributes for that type.
So I also got these replationship: Equipment->DefaultEquipmentType->DefaultEquipmentAttribute.
Now, When I insert new Item and select an equipment I want to copy defaults over to real tables (EquipmentType, EquipmentAttribute).
Is it clear at least a little?
Aside from how you're trying to do this (which isn't working), what specifically are you trying to do?
It may be that this can be resolved by changing / normalizing your paradigm, instead of some kind of exotic code. For example, it looks odd to have a customers table with an orderID field in it. Unless your customers only ever order one thing... I would have expected to see a customers table, an items table, and then an orders table that joined customers with items.
Hope that makes sense -- but anyway, if not, can you post your table structure, and maybe be a little more clear on what you know ahead of time (e.g., I imagine you know who your customers are, and what they ordered...before you do the insert...yes?)
For an INSERT statement you can only access the columns which are in the insert column list, so the solution is to rewrite the statement as a MERGE statement which can access all the columns including columns which are in the INSERT target table for instance IDENTITY columns.
In the demo I've used dbo.INSERTED to emulate the virtual table INSERTED from the trigger.
USE master
GO
IF DB_ID('MergeOutputExample') IS NOT NULL
DROP DATABASE MergeOutputExample
GO
CREATE DATABASE MergeOutputExample
GO
USE MergeOutputExample
GO
DECLARE #Tempequipment TABLE
(EquipmentId int,
DefaultEquipmentId INT,
ID int);
CREATE TABLE dbo.INSERTED
(
EquipmentTypeId int PRIMARY KEY
);
CREATE TABLE dbo.tblEquipmentType
(
ID int IDENTITY(1,1),
Name varchar(50),
EquipmentTypeId int PRIMARY KEY
);
CREATE TABLE dbo.tblDefaultEquipmentType
(
EquipmentTypeId int,
DefaultEquipmentTypeId int IDENTITY(1,1) PRIMARY KEY,
Name varchar(50)
);
INSERT dbo.inserted
(
EquipmentTypeId
)
VALUES (1);
INSERT dbo.tblDefaultEquipmentType
(
EquipmentTypeId,
Name
)
VALUES (
1,
'Hammer'
);
MERGE dbo.tblEquipmentType AS ET
USING (
SELECT DE.EquipmentTypeId,
DE.DefaultEquipmentTypeId,
DE.Name
FROM dbo.tblDefaultEquipmentType DE
INNER JOIN dbo.INSERTED I
ON DE.EquipmentTypeId = I.EquipmentTypeId
) AS DET
ON ET.EquipmentTypeId = DET.EquipmentTypeId
WHEN NOT MATCHED BY TARGET
THEN INSERT
(
Name,
EquipmentTypeID
)
VALUES
(
DET.Name,
DET.EquipmentTypeID
)
OUTPUT DET.EquipmentTypeId,
DET.DefaultEquipmentTypeId,
INSERTED.ID
INTO #Tempequipment;
SELECT *
FROM #Tempequipment;
SELECT *
FROM dbo.tblEquipmentType;