How to populate a table with 1000 rows of sample data? - mysql

For the table bellow:
CREATE TABLE Persons (
ID int NOT NULL,
ModifiedDate datetime,
FirstName varchar(50),
LastName varchar(50),
EMail varchar(30),
PhoneNumber varchar(15),
PRIMARY KEY (ID)
);

You can write a query such as this:
INSERT INTO Persons(ModifiedDate, FirstName, LastName, EMail, PhoneNumber)
SELECT
CURRENT_TIMESTAMP - INTERVAL FLOOR(RAND()* 31536000) SECOND, -- random datetime up to -1 year
CHAR(FLOOR(RAND() * 26)+ ASCII('A')), -- random character between A-Z
CHAR(FLOOR(RAND() * 26)+ ASCII('A')),
CHAR(FLOOR(RAND() * 26)+ ASCII('a')), -- random character between a-z
CHAR(FLOOR(RAND() * 10)+ ASCII('0')) -- random character between 0-9
FROM any_table_with_1000_rows
LIMIT 1000
Any table with 1000 rows could be used. If there isn't one, you can join a table having n rows with itself to get n2 rows.

An easy way is to use https://www.mockaroo.com/ which is designed for that purpose. Create the columns you want and choose SQL as the output. It will make you a nice script.
You could also create an Excel spreadsheet to generate your SQL queries but it is a bit time consuming

Execute the following query, it will insert 1000 dummy rows
BEGIN
DECLARE #RowCount int = 1000,
#Index int = 1
WHILE (#Index <= #RowCount)
BEGIN
INSERT INTO Persons (ID, ModifiedDate, FirstName, LastName, EMail, PhoneNumber)
VALUES (#Index, getdate(), 'FirstName' + CAST(#Index AS varchar(10)), 'LastName' + CAST(#Index AS varchar(10)), 'EMail' + CAST(#Index AS varchar(10)), CAST(#Index AS varchar(10)))
SET #Index += 1
END
END

Related

MYSQL TRIGGER doesn't work sql_extras.sql

Why it doesn't work?
I understand that:
line no.: 9, 21
id int NOT NULL IDENTITY(1, 1), should be AUTO_INCREMENT
id int NOT NULL AUTO_INCREMENT
line no.: 24
wrong column name it can be longs instead of long:
longs decimal(9,6) NOT NULL,
line no.:
out of ; on the end of line 36
out of ; on the end of line 44
line 38, 47 longs instead of long:
INSERT INTO city (city_name, lat, longs, country_id)
but I don't know where is problem below line no.: 91
-- Create new database
CREATE DATABASE lesson7;
USE lesson7;
-- 1. Primary and foreign keys
-- Table: country
CREATE TABLE country (
id int NOT NULL IDENTITY(1, 1),
country_name char(128) NOT NULL,
country_name_eng char(128) NOT NULL,
country_code char(8) NOT NULL,
CONSTRAINT country_ak_1 UNIQUE (country_name),
CONSTRAINT country_ak_2 UNIQUE (country_name_eng),
CONSTRAINT country_ak_3 UNIQUE (country_code),
CONSTRAINT country_pk PRIMARY KEY (id)
);
-- Table: city
CREATE TABLE city (
id int NOT NULL IDENTITY(1, 1),
city_name char(128) NOT NULL,
lat decimal(9,6) NOT NULL,
long decimal(9,6) NOT NULL,
country_id int NOT NULL,
CONSTRAINT city_pk PRIMARY KEY (id),
CONSTRAINT city_country FOREIGN KEY (country_id) REFERENCES country (id)
);
-- Fill the tables
INSERT INTO country (country_name, country_name_eng, country_code)
VALUES ('Deutschland', 'Germany', 'DEU'),
('Srbija', 'Serbia', 'SRB'),
('Hrvatska', 'Croatia', 'HRV'),
('United States of America', 'United States of America', 'USA'),
('Polska', 'Poland', 'POL')
INSERT INTO city (city_name, lat, long, country_id)
VALUES ('Berlin', 52.520008, 13.404954, 1),
('Belgrade', 44.787197, 20.457273, 2),
('Zagreb', 45.815399, 15.966568, 3),
('New York', 40.730610, -73.935242, 4),
('Los Angeles', 34.052235, -118.243683, 4),
('Warsaw', 52.237049, 21.017532, 5)
-- Can we do this?
INSERT INTO city (city_name, lat, long, country_id)
VALUES ('Wien', 48.2084885, 16.3720798, 6);
-- Let's try to delete Poland
DELETE FROM country WHERE id = 5;
-- And check the result
SELECT * FROM city;
SELECT * FROM country;
-- We can remove the constraint using its name
ALTER TABLE city DROP CONSTRAINT city_country;
-- And add it once again with different rescrictions
ALTER TABLE city
ADD CONSTRAINT city_country
FOREIGN KEY (country_id)
REFERENCES country (id)
ON UPDATE CASCADE
ON DELETE CASCADE;
-- Let's try to delete Poland once again
DELETE FROM country WHERE id = 5;
-- And check the results
SELECT * FROM country;
SELECT * FROM city;
-- Triggers
/*
DML (data manipulation language) triggers they react to DML commands.
These are INSERT, UPDATE, and DELETE
DDL (data definition language) triggers they react to DDL commands.
These are CREATE, ALTER, and DROP
*/
/*
DROP <object> IF EXISTS before its creation is helpful in two ways:
1) We could get an arror trying to create a duplicate, we prevent it using DROP
2) If we want to DROP someting non-existent, we can get an error so we check that condidtion first
Combining two above should result in smooth execution
*/
-- Trigger to handle inserts with missing 'country_name' or 'country_name_eng' values
DROP TRIGGER IF EXISTS t_country_insert;
GO
CREATE TRIGGER t_country_insert ON country INSTEAD OF INSERT
AS BEGIN
DECLARE #country_name CHAR(128);
DECLARE #country_name_eng CHAR(128);
DECLARE #country_code CHAR(8);
SELECT #country_name = country_name, #country_name_eng = country_name_eng, #country_code = country_code FROM INSERTED;
IF #country_name IS NULL SET #country_name = #country_name_eng;
IF #country_name_eng IS NULL SET #country_name_eng = #country_name;
INSERT INTO country (country_name, country_name_eng, country_code) VALUES (#country_name, #country_name_eng, #country_code);
END;
-- 'country_name' has NOT NULL constraint, but thanks to the trigger, this insert works fine
SELECT * FROM country;
INSERT INTO country (country_name_eng, country_code) VALUES ('United Kingdom', 'UK');
SELECT * FROM country;
-- Trigger to prevent removal of record from parent table if there are records in child table referencing it
DROP TRIGGER IF EXISTS t_country_delete;
GO
CREATE TRIGGER t_country_delete ON country INSTEAD OF DELETE
AS BEGIN
DECLARE #id INT;
DECLARE #count INT;
SELECT #id = id FROM DELETED;
SELECT #count = COUNT(*) FROM city WHERE country_id = #id;
IF #count = 0
DELETE FROM country WHERE id = #id;
ELSE
THROW 51000, 'can not delete - country is referenced in other tables', 1;
END;
-- Example
SELECT * FROM country;
SELECT * FROM city;
DELETE FROM country WHERE id = 4;
/*
Functions - idea behind them is to avoid writing the same code over and over again
*/
-- Example: function returning if point on the map is located in a western or eastern hemisphere
-- Input: single decimal value (longitude)
-- Output: single char value (position)
-- It's an example of a "scalar-valued function" - returns a single value
CREATE FUNCTION east_or_west (
#long DECIMAL(9,6)
)
RETURNS CHAR(4) AS
BEGIN
DECLARE #return_value CHAR(4);
SET #return_value = 'same';
IF (#long > 0.00) SET #return_value = 'east';
IF (#long < 0.00) SET #return_value = 'west';
RETURN #return_value
END;
-- Examples
SELECT * FROM city;
SELECT city_name, dbo.east_or_west(long) AS 'position'
FROM city;
-- Example: function returning cities from table 'city' located to the east of a given point
-- Input: single decimal value (longitude of a point)
-- Output: filtered table 'city'
-- It's an example of a "table-valued function" - returns a table (multiple values)
CREATE FUNCTION east_from_long (
#long DECIMAL(9,6)
)
RETURNS TABLE AS
RETURN
SELECT *
FROM city
WHERE city.long > #long;
-- Example
SELECT *
FROM east_from_long(0.00);
/*
Stored procedures - idea behind them is to put multiple operations
(inserting, updating, deleting, retrieving data) into one "black box" that can be called multiple times
using various parameters
*/
DROP PROCEDURE IF EXISTS p_cities_all;
GO
CREATE PROCEDURE p_cities_all
-- procedure returns all rows from the customer table
AS BEGIN
SELECT *
FROM city;
END;
-- Execute the procedure with EXEC, procedure uses no parameters
EXEC p_cities_all;
-- Another example, procedure returns the entire row for the given id
DROP PROCEDURE IF EXISTS p_city;
GO
CREATE PROCEDURE p_city (#id INT)
AS BEGIN
SELECT *
FROM city
WHERE id = #id;
END;
-- Execute using EXEC and providing the value for a parameter (id of a row)
EXEC p_city 4;
SELECT * FROM country;
SELECT * FROM city;
-- Example: procedure inserting city from germany (no 'country_id' value is needed while inserting records)
DROP PROCEDURE IF EXISTS p_city_in_germany_insert;
GO
CREATE PROCEDURE p_city_in_germany_insert (#city_name CHAR(128), #lat DECIMAL(9, 6), #long DECIMAL(9, 6))
AS BEGIN
INSERT INTO city(city_name, lat, long, country_id)
VALUES (#city_name, #lat, #long, 1);
END;
-- Example, let's insert Munich to our table
SELECT * FROM city;
EXEC p_city_in_germany_insert 'Munich', 48.13743, 11.57549;
SELECT * FROM city;
-- Example: deleting rows based on 'id'
DROP PROCEDURE IF EXISTS p_city_delete;
GO
CREATE PROCEDURE p_city_delete (#id INT)
AS BEGIN
DELETE
FROM city
WHERE id = #id;
END;
-- Example, delete city with id = 1
EXEC p_city_delete 1;
-- Results
SELECT * FROM city;

SQL: GROUP BY Clause for Comma Separated Values

Can anyone help me how to check duplicate values from multiple comma separated value. I have a customer table and in that one can insert multiple comma separated contact number and I want to check duplicate values from last five digits.For reference check screenshot attached and the required output is
contact_no. count
97359506775 -- 2
390558073039-- 1
904462511251-- 1
I would advise you to redesign your database schema, if possible. Your current database violates First Normal Form since your attribute values are not indivisible.
Create a table where id together with a single phone number constitutes a key, this constraint enforces that no duplicates occur.
I don't remember much but I will try to put the idea (it's something which I had used a long time ago):
Create a table value function which will take the id and phone number as input and then generate a table with id and phone numbers and return it.
Use this function in query passing id and phone number. The query is such that for each id you get as many rows as the phone numbers. CROSS APPLY/OUTER APPLY needs to be used.
Then you can check for the duplicates.
The function would be something like this:
CREATE FUNCTION udf_PhoneNumbers
(
#Id INT
,#Phone VARCHAR(300)
) RETURNS #PhonesTable TABLE(Id INT, Phone VARCHAR(50))
BEGIN
DECLARE #CommaIndex INT
DECLARE #CurrentPosition INT
DECLARE #StringLength INT
DECLARE #PhoneNumber VARCHAR(50)
SELECT #StringLength = LEN(#Phone)
SELECT #CommaIndex = -1
SELECT #CurrentPosition = 1
--index is 1 based
WHILE #CommaIndex < #StringLength AND #CommaIndex <> 0
BEGIN
SELECT #CommaIndex = CHARINDEX(',', #Phone, #CurrentPosition)
IF #CommaIndex <> 0
SELECT #PhoneNumber = SUBSTRING(#Phone, #CurrentPosition, #CommaIndex - #CurrentPosition)
ELSE
SELECT #PhoneNumber = SUBSTRING(#Phone, #CurrentPosition, #StringLength - #CurrentPosition + 1)
SELECT #CurrentPosition = #CommaIndex + 1
INSERT INTO #UsersTable VALUES(#Id, #PhoneNumber)
END
RETURN
END
Then run CROSS APPLY query:
SELECT
U.*
,UD.*
FROM yourtable U CROSS APPLY udf_PhoneNumbers(Userid, Phone) UD
This will give you the table on which you can run query to find duplicate.

Query to get list of all additions , deletions and modifictaions done in the mysql database in the past

My application is AngularJs + RubyOnRails + MySQL.
I need to query in rails to list all the changes made in the database in the past ie. Addition, Deletion or Modification made in any table in the database along with the datetime when the change occurred , the action(add/delete/modify) and the details of the changes eg:
DateTime |Action | Table Name | User
Mar-21-2016 12:53:49 AM | ADD |Activity | ari.gunawan
For table 'Activity' the record with the Record ID 61327 the following
changes changes were made.: [EntityRef]='976' , [ContactsRef]='702' ,
[EmailCC]='' , [EmailFromName]='' , [EmailFrom]='' ,
[ActualDuration]='0' , [ContactName]='Ms Novita' ,
[CreatedDate]='NULL' , [CreatedByRef]='NULL' , [AssignedToRef]='33' ,
[Comments]='Yth. Pak Arie,
Mohon bantuannya untuk memposting iklan lowongan
kerja untuk salah satu divisi usaha grup sekolah kami.
Materi Iklan terlampir. Terima
kasih, Pak Arie. Salam
Sejawat, Novita' ,
[ContactEmail]='hrdmutiarabunda#gmail.com' , [EmailSubject]='' ,
[ActualStartDate]='Mar-21-2016 07:53 AM' ,
[ActualCompletedDate]='21-Mar-2016 07:53:00 AM' ,
[ContactPhoneNumber]='022 7211200' , [ActivityPriorityRef]='2' ,
[LastModifiedDate]='NULL' , [LastModifiedByRef]='NULL' ,
[EmailBody]='' , [ActivityTypeRef]='3' , [EmailBCC]='' ,
[TempBillAddressCityStateProvZipPostal]='BANDUNG,' ,
[ActivityStatusRef]='3' , [FollowUpFromActivityNoRef]='NULL' ,
[DueDateStart]='Mar-21-2016 07:53 AM' , [EmailTemplateRef]='NULL' ,
[EmailTo]=''
All the tables in the database have the fields created_at,created_by,updated_at,updated_by.
How can I do the above in Rails?
you have to maintain a table with fields created_at,created_by,updated_at,updated_by to store these data with triggers for add/delete/modify.
here some example for triggers in mssql (triggers are event responders that happens when user do interact with the database, they will trig automatically)
INSERT
/*
InsertProductTrigger.sql creates a trigger that fires
after an INSERT statement is performed on the
Products table
*/
CREATE TRIGGER InsertProductTrigger
ON Products
AFTER INSERT
AS
-- don't return the number of rows affected
SET NOCOUNT ON
-- declare an int variable to store the new
-- ProductID
DECLARE #NewProductID int
-- get the ProductID of the new row that
-- was added to the Products table
SELECT #NewProductID = ProductID
FROM inserted
-- add a row to the ProductAudit table
INSERT INTO ProductAudit ( Action )
VALUES ('Product added with ProductID of ' + CONVERT(nvarchar, #NewProductID) )
 
UPDATE
/*
UpdateUnitPriceProductTrigger.sql creates a trigger
that fires after an UPDATE statement is performed on the
the UnitPrice column of the Products table.
If the reduction of the unit price of a product is
greater than 25% then a row is added to the ProductAudit table
to audit the change.
*/
CREATE TRIGGER UpdateUnitPriceProductTrigger
ON Products
AFTER UPDATE
AS
-- don't return the number of rows affected
SET NOCOUNT ON
-- only run the code if the UnitPrice column
-- was modified
IF UPDATE(UnitPrice)
BEGIN
-- declare an int variable to store the
-- ProductID
DECLARE #MyProductID int
-- declare two money variables to store the
-- old unit price and the new unit price
DECLARE #OldUnitPrice money
DECLARE #NewUnitPrice money
-- declare a float variable to store the price
-- reduction percentage
DECLARE #PriceReductionPercentage float
-- get the ProductID of the row that
-- was modified from the inserted table
SELECT #MyProductID = ProductID
FROM inserted
-- get the old unit price from the deleted table
SELECT #OldUnitPrice = UnitPrice
FROM deleted
WHERE ProductID = #MyProductID
-- get the new unit price from the inserted table
SELECT #NewUnitPrice = UnitPrice
FROM inserted
-- calculate the price reduction percentage
SET #PriceReductionPercentage =
((#OldUnitPrice -#NewUnitPrice) / #OldUnitPrice) * 100
-- if the price reduction percentage is greater than 25%
-- then audit the change by adding a row to the PriceAudit table
IF (#PriceReductionPercentage > 25)
BEGIN
-- add a row to the ProductAudit table
INSERT INTO ProductAudit (Action )
VALUES ( 'UnitPrice of ProductID #' +CONVERT(nvarchar, #MyProductID) +
' was reduced by ' + CONVERT(nvarchar, #PriceReductionPercentage) + '%' )
END
END
 
DELETE
/*
DeleteProductTrigger.sql creates a trigger that fires
after a DELETE statement is performed on the
Products table
*/
CREATE TRIGGER DeleteProductTrigger
ON Products
AFTER DELETE
AS
-- don't return the number of rows affected
SET NOCOUNT ON
-- declare an int variable to store the
-- ProductID
DECLARE #NewProductID int
-- get the ProductID of the row that
-- was removed from the Products table
SELECT #NewProductID = ProductID
FROM deleted
-- add a row to the ProductAudit table
INSERT INTO ProductAudit (Action)
VALUES ('Product #' +CONVERT(nvarchar, #NewProductID) +' was removed' )

How can I create a function in MySQL for add elements in a table?

I would like to add elements in a table like this:
Codigo Name Lastname Date Sex Salary
1 name1 lastname1 random random random
2 name2 lastname2 random random random
3 name3 lastname3 random random random
4 name4 lastname4 random random random
Date is a date random betweem years 2000 - 2015
Sex is random boolean 1 or 0
Salary is a random float between 500.00 and 5000.00
is that possible? How can I do that? I don't know even how can I do the sentence while
CREATE OR REPLACE FUNCTION inserting(integer varying, character varying, character varying, date, boolean, float varying) RETURNS void
AS $$
begin
insert into trabajador(codigo, name, lastname, date, sex, salary) values ($1,$2,$3,$4,$5,$6);
end;
$$
LANGUAGE 'plpgsql';
Use rand() to generate a float number between 0 and 1. Then something like this should generate your random data:
insert into yourtable values
( 1,
'John',
'Doe',
DATE_ADD('2000-01-01', INTERVAL (RAND()*15*365) DAY),
FLOOR(RAND()*10) % 2,
500+ROUND(RAND() * 4500,2)
);
SQL Fiddle Demo
This should be a procedure, not a function, since it doesn't return anything. Then use a WHILE loop in the procedure to insert many rows.
To create many
DELIMITER $$
CREATE PROCEDURE inserting(rowcount INT)
BEGIN
SET #i = 0;
SET #codigo = (SELECT MAX(codigo)+1 FROM trabajador);
WHILE #i < rowcount
DO
SET #name = CONCAT('name', #codigo);
SET #lastname = CONCAT('lastname', #codigo);
SET #date = DATE_ADD('2000-01-01', INTERVAL (RAND()*15*365) DAY);
SET #sex = FLOOR(RAND() * 2);
SET #salary = 500.0 + RAND() * 4500.0;
INSERT INTO trabajador (codigo, name, lastname, date, sex, salary)
VALUES (#codigo, #name, #lastname, #data, #sec, #salary);
SET #i = #i + 1;
SET #codigo = #codigo + 1;
END WHILE;
END;
$$
DELIMITER ;
To add 500 rows, use CALL inserting(500);
Using RAND() function
CREATE TABLE tbl(Codigo INT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY
,Name VARCHAR(25) NOT NULL
,LastName VARCHAR(25) NOT NULL
,Date DATE NOT NULL
,Sex BOOLEAN NOT NULL
,Salary FLOAT NOT NULL
);
INSERT INTO tbl(Name, LastName, Date, Sex, Salary)
VALUES('name1',
'lastname1',
FROM_UNIXTIME(UNIX_TIMESTAMP('2000-01-01 00:00:00') + FLOOR(0 + (RAND() * 157680000))),
FLOOR(RAND() * 10) % 2,
FLOOR(RAND() * 5000) + 500);
SQLFiddle

How to copy data from one table to another "EXCEPT" one field

How to INSERT into another table except specific field
e.g
TABLE A
ID(auto_inc) CODE NAME
1 001 TEST1
2 002 TEST2
I want to insert CODE and NAME to another table, in this case TABLE B but except ID because it is auto increment
Note: I don't want to use "INSERT INTO TABLE B SELECT CODE, NAME FROM TABLE A", because I have an existing table with around 50 fields and I don't want to write it one by one
Thanks for any suggests and replies
This can't be done without specifying the columns (excludes the primary key).
This question might help you. Copy data into another table
You can get all the columns using information_schema.columns:
select group_concat(column_name separator ', ')
from information_schema.columns c
where table_name = 'tableA' and
column_name <> 'id';
This gives you the list. Then past the list into your code. You can also use a prepared statement for this, but a prepared statement might be overkill.
If this is a one time thing?
If yes, do the insert into tableA (select * from table B)
then Alter the table to drop the column that your dont need.
I tried to copy from a table to another one with one extra field.
source table is TERRITORY_t
* the principle is to create a temp table identical to the source table, adjust column fields of the temp table and copy the content of the temp table to the destination table.
This is what I did:
create a temp table called TERRITORY_temp
generate SQL by running export
CREATE TABLE IF NOT EXISTS TERRITORY_temp (
Territory_Id int(11) NOT NULL,
Territory_Name varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (Territory_Id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
copy over with
INSERT INTO TERRITORY_temp (Territory_Id, Territory_Name) VALUES
(1, 'SouthEast'),
(2, 'SouthWest'),
(3, 'NorthEast'),
(4, 'NorthWest'),
(5, 'Central');
or
INSERT INTO TERRITORY_temp
SELECT * from TERRITORY_t
add the extra field(s) to match with the new table
copy from the temp table to the destination table
INSERT INTO TERRITORY_new
SELECT * from TERRITORY_temp
Please provide feedback.
Step 1. Create stored procedure
CREATE PROCEDURE CopyDataTable
#SourceTable varchar(255),
#TargetTable varchar(255),
#SourceFilter nvarchar(max) = ''
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SourceColumns VARCHAR(MAX)=''
DECLARE #TargetColumns VARCHAR(MAX)=''
DECLARE #Query VARCHAR(MAX)=''
SELECT
#SourceColumns = ISNULL(#SourceColumns +',', '') + T.COLUMN_NAME
FROM
(
select name as COLUMN_NAME from sys.all_columns
where object_id = (select object_id from sys.tables where name = #SourceTable)
and is_identity = 0
)T
SELECT
#TargetColumns = ISNULL(#TargetColumns +',', '') + T.COLUMN_NAME
FROM
(
select name as COLUMN_NAME from sys.all_columns
where object_id = (select object_id from sys.tables where name = #TargetTable)
and is_identity = 0
)T
set #Query = 'INSERT INTO ' + #TargetTable + ' (' + SUBSTRING(#TargetColumns,2 , 9999) + ') SELECT ' + SUBSTRING(#SourceColumns,2 , 9999) + ' FROM ' + #SourceTable + ' ' + #SourceFilter;
PRINT #Query
--EXEC(#Query)
END
GO
Step 2. Run stored procedure
use YourDatabaseName
exec dbo.CopyDataTable 'SourceTable','TargetTable'
Explanations
a) dbo.CopyDataTable will transfer all data from SourceTable to TargetTable, except field with Identity
b) You can apply filter when call stored procedure, in order to transfer only row based on criteria
exec dbo.CopyDataTable 'SourceTable','TargetTable', 'WHERE FieldName=3'
exec dbo.CopyDataTable 'SourceTable','TargetTable', 'WHERE FieldName=''TextValue'''
c) Remove -- from --EXEC(#Query) WHEN finish