blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 133 | path stringlengths 3 276 | src_encoding stringclasses 33
values | length_bytes int64 23 9.61M | score float64 2.52 5.28 | int_score int64 3 5 | detected_licenses listlengths 0 44 | license_type stringclasses 2
values | text stringlengths 23 9.43M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
e79f1d19584d11906451f16174893bdfa428d2c0 | SQL | danstorey901/my-sql-scripts | /UPDATESTUDENTINTOTABLE.sql | UTF-8 | 336 | 3.078125 | 3 | [] | no_license | --INSERT A NEW STUDENT THAT HAS RECENTLY ENROLLED. STUDENT INFO = NAME: NOAH PHENSE, STATE: GA, SAT:1235, GPA:3.15, MAJOR:MATH
/*
Insert Student
(Firstname,Lastname, StateCode, SAT, GPA, MajorId)
VALUES
('Noah','Phense','GA','1235','3.15',
(select Id from Major Where Description = 'Math'));
*/
select * from Student order by id desc; | true |
10a6c91160c7b46e183655f91cce7c4feb9f8d21 | SQL | glf134/ruoyi | /gapMenu.sql | UTF-8 | 1,952 | 2.65625 | 3 | [] | no_license | -- 菜单 SQL
insert into sys_menu (menu_name, parent_id, order_num, url, menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark)
values('安全隔离网闸数据元(GAP)', '2000', '1', '/datasync/gap', 'C', '0', 'datasync:gap:view', '#', 'admin', sysdate(), '', null, '安全隔离网闸数据元(GAP)菜单');
-- 按钮父菜单ID
SELECT @parentId := LAST_INSERT_ID();
-- 按钮 SQL
insert into sys_menu (menu_name, parent_id, order_num, url, menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark)
values('安全隔离网闸数据元(GAP)查询', @parentId, '1', '#', 'F', '0', 'datasync:gap:list', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, url, menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark)
values('安全隔离网闸数据元(GAP)新增', @parentId, '2', '#', 'F', '0', 'datasync:gap:add', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, url, menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark)
values('安全隔离网闸数据元(GAP)修改', @parentId, '3', '#', 'F', '0', 'datasync:gap:edit', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, url, menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark)
values('安全隔离网闸数据元(GAP)删除', @parentId, '4', '#', 'F', '0', 'datasync:gap:remove', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, url, menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark)
values('安全隔离网闸数据元(GAP)导出', @parentId, '5', '#', 'F', '0', 'datasync:gap:export', '#', 'admin', sysdate(), '', null, '');
| true |
3a7ec4cb4a48af53c3ec84cdc396f2bf34122eeb | SQL | komour/database-management | /hw6/4.3r.sql | UTF-8 | 301 | 3.421875 | 3 | [] | no_license | SELECT
s.StudentId
FROM Students s
WHERE NOT EXISTS (SELECT
s.StudentId
FROM Lecturers l,
Plan p
WHERE NOT EXISTS (SELECT
m.StudentId,
m.CourseId
FROM Marks m
WHERE m.StudentId = s.StudentId
AND m.CourseId = p.CourseId)
AND l.LecturerId = p.LecturerId
AND l.LecturerName = :LecturerName); | true |
e3d62fe2b25cff8adea6c64ff3fd3f74608011ca | SQL | LotusEliza/SOAP | /task2/server/lotushealth (4).sql | UTF-8 | 5,619 | 3.265625 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jun 13, 2019 at 04:15 PM
-- Server version: 5.7.26-0ubuntu0.18.04.1
-- PHP Version: 5.6.40-8+ubuntu18.04.1+deb.sury.org+1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cars_soap`
--
-- --------------------------------------------------------
--
-- Table structure for table `brands`
--
CREATE TABLE `brands` (
`id` int(11) NOT NULL,
`brand` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `brands`
--
INSERT INTO `brands` (`id`, `brand`) VALUES
(1, 'Aston-Martin'),
(2, 'Audi'),
(3, 'Bugatti');
-- --------------------------------------------------------
--
-- Table structure for table `cars`
--
CREATE TABLE `cars` (
`id` int(11) NOT NULL,
`model_id` int(11) NOT NULL,
`brand_id` int(11) NOT NULL,
`year` int(11) NOT NULL,
`capacity` int(11) NOT NULL,
`speed` int(11) NOT NULL,
`price` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cars`
--
INSERT INTO `cars` (`id`, `model_id`, `brand_id`, `year`, `capacity`, `speed`, `price`) VALUES
(1, 1, 1, 1965, 1, 200, 1000),
(2, 2, 1, 2005, 2, 170, 2000),
(3, 3, 2, 2019, 2, 270, 10000),
(4, 4, 2, 2019, 2, 320, 20000),
(5, 5, 3, 1900, 1, 90, 12000),
(6, 6, 3, 1903, 1, 100, 25000);
-- --------------------------------------------------------
--
-- Table structure for table `cars_colors`
--
CREATE TABLE `cars_colors` (
`id` int(11) NOT NULL,
`car_id` int(11) NOT NULL,
`color_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cars_colors`
--
INSERT INTO `cars_colors` (`id`, `car_id`, `color_id`) VALUES
(1, 1, 3),
(2, 2, 1),
(3, 3, 2),
(4, 4, 3),
(5, 5, 2),
(6, 6, 1);
-- --------------------------------------------------------
--
-- Table structure for table `colors`
--
CREATE TABLE `colors` (
`id` int(11) NOT NULL,
`color` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `colors`
--
INSERT INTO `colors` (`id`, `color`) VALUES
(1, 'red'),
(2, 'white'),
(3, 'green');
-- --------------------------------------------------------
--
-- Table structure for table `models`
--
CREATE TABLE `models` (
`id` int(11) NOT NULL,
`model` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `models`
--
INSERT INTO `models` (`id`, `model`) VALUES
(1, 'DB5'),
(2, 'V8 Vantage'),
(3, 'A3'),
(4, 'S3'),
(5, 'Type 2'),
(6, 'Type 5');
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders_soap` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`surname` varchar(255) NOT NULL,
`car_id` int(11) NOT NULL,
`payment` enum('credit_cart','cash') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `brands`
--
ALTER TABLE `brands`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `cars`
--
ALTER TABLE `cars`
ADD PRIMARY KEY (`id`),
ADD KEY `cars_fk0` (`model_id`),
ADD KEY `cars_fk1` (`brand_id`);
--
-- Indexes for table `cars_colors`
--
ALTER TABLE `cars_colors`
ADD UNIQUE KEY `id` (`id`),
ADD KEY `cars_colors_fk0` (`car_id`),
ADD KEY `cars_colors_fk1` (`color_id`);
--
-- Indexes for table `colors`
--
ALTER TABLE `colors`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `models`
--
ALTER TABLE `models`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `orders`
--
ALTER TABLE `orders_soap`
ADD PRIMARY KEY (`id`),
ADD KEY `car_id` (`car_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `brands`
--
ALTER TABLE `brands`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `cars`
--
ALTER TABLE `cars`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `cars_colors`
--
ALTER TABLE `cars_colors`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `colors`
--
ALTER TABLE `colors`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `models`
--
ALTER TABLE `models`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders_soap` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `cars`
--
ALTER TABLE `cars`
ADD CONSTRAINT `cars_fk0` FOREIGN KEY (`model_id`) REFERENCES `models` (`id`),
ADD CONSTRAINT `cars_fk1` FOREIGN KEY (`brand_id`) REFERENCES `brands` (`id`);
--
-- Constraints for table `cars_colors`
--
ALTER TABLE `cars_colors`
ADD CONSTRAINT `cars_colors_fk0` FOREIGN KEY (`car_id`) REFERENCES `cars` (`id`),
ADD CONSTRAINT `cars_colors_fk1` FOREIGN KEY (`color_id`) REFERENCES `colors` (`id`);
--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
ADD CONSTRAINT `fk_foreign_key_name` FOREIGN KEY (`car_id`) REFERENCES `cars` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
8323a7fe2bbe2ae2c6a36491e6f151b55c47de12 | SQL | OscarMesa/AppIngEgr | /protected/data/REQUERIMIENTOS/03/dia.sql | UTF-8 | 1,907 | 3.9375 | 4 | [] | no_license | -----------------------------------------------
-- Función que invoca el procedimiento
-----------------------------------------------
DROP FUNCTION IF EXISTS saldoDia;
DELIMITER //
CREATE FUNCTION saldoDia(usuario INT(5)) RETURNS DOUBLE
BEGIN
DECLARE fecha_menor DATE;
-- DECLARE saldo_dia DOUBLE;
SET fecha_menor = (SELECT MIN(t.fecha)
FROM datamartingresos.fac_ingresos_diarios fac
INNER JOIN datamartingresos.dim_tiempo t ON fac.fecha_ingreso = t.id_fecha AND fac.id_persona = usuario
LIMIT 1);
CALL saldoDiaRecursiva(fecha_menor, NOW(), usuario, @saldo_dia);
RETURN @saldo_dia;
END;
//
-----------------------------------------------
-- Procedimiento
-----------------------------------------------
DROP PROCEDURE IF EXISTS saldoDiaRecursiva;
DELIMITER //
CREATE PROCEDURE saldoDiaRecursiva(IN fecha_menor DATE, IN fecha_actual DATE, IN usuario INT(5), OUT saldo_dia DOUBLE)
BEGIN
DECLARE ingresos_dia DOUBLE;
DECLARE egresos_dia DOUBLE;
SET saldo_dia = 0;
WHILE fecha_menor <= fecha_actual DO
SET ingresos_dia = (SELECT fac.total_ingreso_dia
FROM datamartingresos.dim_tiempo t
INNER JOIN datamartingresos.fac_ingresos_diarios fac ON t.id_fecha = fac.fecha_ingreso
WHERE t.fecha = fecha_menor AND fac.id_persona = usuario
LIMIT 1);
IF ingresos_dia IS NULL THEN
SET ingresos_dia = 0;
END IF;
SET egresos_dia = (SELECT fac.total_egreso_dia
FROM datamartegresos.dim_tiempo t
INNER JOIN datamartegresos.fac_egresos_diarios fac ON t.id_fecha = fac.fecha_egreso
WHERE t.fecha = fecha_menor AND fac.id_persona = usuario
LIMIT 1);
IF egresos_dia IS NULL THEN
SET egresos_dia = 0;
END IF;
SET saldo_dia = saldo_dia + ingresos_dia - egresos_dia;
SET fecha_menor = DATE_ADD(fecha_menor,INTERVAL 1 DAY);
END WHILE;
END
// | true |
f7598d067c73875057274a490b64ca21dbc9e6b4 | SQL | nstasino/covid19-dashboard | /scripts/schema.sql | UTF-8 | 4,712 | 3.75 | 4 | [] | no_license | -- Covid 19 Schema
-- Table: public.covid19
DROP TABLE public.covid19 CASCADE;
CREATE TABLE IF NOT EXISTS public.covid19
(
fips character varying(20) COLLATE pg_catalog."default",
admin2 character varying(60) COLLATE pg_catalog."default",
province character varying(60) COLLATE pg_catalog."default",
country character varying(60) COLLATE pg_catalog."default",
latitude double precision,
longitude double precision,
confirmed integer,
deaths integer,
recovered integer,
active integer,
combined_key character varying(120) COLLATE pg_catalog."default",
last_update timestamp without time zone,
file_date date DEFAULT '2020-04-07'::date,
"Incidence_Rate" double precision,
"Case-Fatality_Ratio" double precision
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.covid19
OWNER to superset;
-- Table: public.covid_lookup
DROP TABLE public.covid_lookup CASCADE;
CREATE TABLE IF NOT EXISTS public.covid_lookup
(
uid integer,
iso2 character varying(2) COLLATE pg_catalog."default",
iso3 character varying(3) COLLATE pg_catalog."default",
code3 integer,
fips integer,
admin2 character varying(60) COLLATE pg_catalog."default",
province_state character varying(60) COLLATE pg_catalog."default",
country_region character varying(60) COLLATE pg_catalog."default",
lat double precision,
long_ double precision,
combined_key character varying(60) COLLATE pg_catalog."default",
population bigint
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.covid_lookup
OWNER to superset;
CREATE INDEX idx_country_btree ON public.covid19 USING btree (country);
CREATE INDEX idx_file_date_btree ON public.covid19 USING btree (file_date);
ALTER TABLE public.covid19 CLUSTER ON idx_file_date_btree;
CREATE INDEX idx_province_hash ON public.covid19 USING hash (province);
-- Table: public.state_abbreviation
DROP TABLE public.state_abbreviation CASCADE;
CREATE TABLE IF NOT EXISTS public.state_abbreviation
(
state character varying(100) COLLATE pg_catalog."default",
abbr character(2) COLLATE pg_catalog."default"
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.state_abbreviation
OWNER to superset;
CREATE INDEX idx_state_hash
ON public.state_abbreviation USING hash
(state COLLATE pg_catalog."default")
TABLESPACE pg_default;
-- View: public.sunkey
DROP VIEW public.sunkey;
CREATE OR REPLACE VIEW public.sunkey AS
WITH totals AS (
SELECT covid19.country,file_date,
sum(covid19.confirmed) AS confirmed,
sum(covid19.deaths) AS deaths,
sum(covid19.recovered) AS recovered
FROM covid19
GROUP BY covid19.country,file_date
)
SELECT totals.country,
'deaths'::text AS target,
totals.deaths AS value_final,
file_date
FROM totals
UNION
SELECT totals.country,
'recovered'::text AS target,
totals.recovered AS value_final,
file_date
FROM totals
UNION
SELECT totals.country,
'under treatment'::text AS target,
totals.confirmed - totals.deaths - totals.recovered AS value_final,
file_date
FROM totals;
-- View: public.by_state
DROP VIEW public.by_state;
CREATE OR REPLACE VIEW public.by_state AS
SELECT concat('US-', abbrvs.abbr) AS code,
abbrvs.state,
covid_lookup.iso2,
covid_lookup.iso3,
covid19.deaths,
covid19.confirmed,
covid19.recovered,
covid19.country,
covid19.province,
covid19.admin2,
covid19.latitude,
covid19.longitude,
covid_lookup.population,
covid19.file_date
FROM covid_lookup,
covid19,
state_abbreviation abbrvs
WHERE covid_lookup.province_state::text = covid19.province::text AND covid_lookup.country_region::text = 'US'::text AND covid19.country::text = 'United States'::text AND abbrvs.state::text = covid19.province::text;
ALTER TABLE public.by_state
OWNER TO superset;
-- View: public.covid_pdf
DROP VIEW public.covid_pdf;
CREATE OR REPLACE VIEW public.covid_pdf AS
SELECT sum(covid19.deaths) AS sum,
covid19.file_date,
covid19.country,
sum(covid19.confirmed) - lag(sum(covid19.confirmed), 1) OVER (PARTITION BY covid19.country ORDER BY covid19.file_date) AS confirmed,
sum(covid19.deaths) - lag(sum(covid19.deaths), 1) OVER (PARTITION BY covid19.country ORDER BY covid19.file_date) AS deaths,
sum(covid19.recovered) - lag(sum(covid19.recovered), 1) OVER (PARTITION BY covid19.country ORDER BY covid19.file_date) AS recovered
FROM covid19
GROUP BY covid19.country, covid19.file_date
ORDER BY covid19.country, covid19.file_date;
ALTER TABLE public.covid_pdf
OWNER TO superset;
| true |
a3ad84c54f9013bd7f946c132ac646cc0b95bfdd | SQL | NHSRC/facilities-assessment-server | /src/main/resources/db/migration/V100__ChecklistCanBelongToMultipleAssessentTools.sql | UTF-8 | 398 | 3.109375 | 3 | [] | no_license | CREATE TABLE assessment_tool_checklist
(
id SERIAL PRIMARY KEY,
assessment_tool_id INT REFERENCES assessment_tool (id) NOT NULL,
checklist_id INT REFERENCES checklist (id) NOT NULL
);
insert into assessment_tool_checklist (assessment_tool_id, checklist_id) select assessment_tool_id, id from checklist;
alter table checklist drop column assessment_tool_id; | true |
1b82f8f8345d49a2f85854f1ab907230e1418de6 | SQL | Trostnick/Internet_shop | /src/main/resources/insert.sql | UTF-8 | 1,247 | 3.203125 | 3 | [] | no_license | use demo;
insert into user_status
values (1, 'ROLE_client'),
(2, 'ROLE_manager'),
(3, 'ROLE_admin');
insert into order_status
values (1, 'in cart'),
(2, 'booked'),
(3, 'payed'),
(4, 'delivered'),
(5, 'finished');
insert into camp_type
values (1, 'stationary'),
(2, 'tent'),
(3, 'day stay');
#пользователь(администратор) с логином first и паролем qwerty123
#пользователь(продавец) с логином manager и паролем manager
#пользователь(покупатель) с логином user и паролем useruser
insert into user
values (1, 'Main', 'first', '$2a$10$/1j4vr//s8o4ovCN64rMXesDIKhTs80jZs0KtufvmRzABT5BLTBZm', 0, 3),
(2, 'Manager', 'manager', '$2a$10$HZ1SaYuzmkY2yH7XYYvGluYFlzA1Bu7prbRSmd7jk2Qrx3hGbTJJi', 0, 2),
(3, 'User', 'user', '$2a$10$nYiknDuy4e2ZvV4RmYTbLOXjIwjTP/cr2eJbjLmrDYPagcpPqCGN2', 0, 1);
#тестовые данные
insert into place
values (1, 'Place1', 'far far away', 'something', 0),
(2, 'Place2', 'far', 'something', 1),
(3, 'Not first Place', 'very near', 'something', 0),
(4, 'Place not 1st', 'this', 'something', 0);
commit;
| true |
4d866bdceaff56ca9e72ace2f542881a30e8abab | SQL | itarocha/betesda | /src/main/resources/sql/leito_by_hospede_leito_id.sql | UTF-8 | 227 | 2.6875 | 3 | [] | no_license | SELECT new br.com.itarocha.betesda.model.LeitoVO(l.id, l.numero, q.id, q.numero, l.tipoLeito)
FROM HospedeLeito hospedeLeito
INNER JOIN hospedeLeito.leito l
INNER JOIN l.quarto q
WHERE hospedeLeito.id = :id | true |
1bc34d01eed7e87f323263dcac11346928ccd372 | SQL | JonathanPMohan/Chinook-Excercises | /brazil_customers.sql | UTF-8 | 78 | 2.515625 | 3 | [] | no_license | -- brazil_customers --
Select *
from dbo.Customer c
where c.Country = 'BRAZIL' | true |
c275d44959d7e30d3f59ba7bc8d7fd15ecef7edb | SQL | IVSEZ/mysqlbis | /Analysis/PRASLIN_customers.sql | UTF-8 | 1,759 | 3.375 | 3 | [] | no_license | select
reportdate, clientarea, clientcode, currentdebt, IsAccountActive, AccountActivityStage
, clientname, clientclass, clientaddress
, clientemail, clientnin, clientphone
, clean_mxk_name, clean_mxk_interface
, firstactivedate, lastactivedate, dayssincelastactive, firstcontractdate, firstpaymentdate, lastpaymentdate
, lastpaidamount, totalpaymentamount, TotalPaymentAmount2019, AvgMonthlyPayment2019, TotalPaymentAmount2018, AvgMonthlyPayment2018
from rcbill_my.rep_custconsolidated
where (clientarea in ('PRASLIN') or clientaddress like '%PRASLIN%')
-- and IsAccountActive='InActive'
;
select
reportdate, clientarea, clientcode, currentdebt, IsAccountActive, AccountActivityStage
, clientname, clientclass, clientaddress
, clientemail, clientnin, clientphone
, clean_mxk_name, clean_mxk_interface
, firstactivedate, lastactivedate, dayssincelastactive, firstcontractdate, firstpaymentdate, lastpaymentdate
, lastpaidamount, totalpaymentamount, TotalPaymentAmount2019, AvgMonthlyPayment2019, TotalPaymentAmount2018, AvgMonthlyPayment2018
from rcbill_my.rep_custconsolidated
where clientcode in
(
select clientcode from rcbill_my.clientstats
where region='PRASLIN' and
(`services` = 'All' or `services` like '%Voice%')
)
;
/*
-- limit 100;
select clientarea, count(clientcode) as clients from rcbill_my.rep_custconsolidated
group by clientarea
;
select * from rcbill_my.rep_custconsolidated where clientarea='Praslin';
select * from rcbill_my.clientstats
where region='PRASLIN' and
(`Intel Voice 10`>0 or `Intel Voice 20`>0 or `Voice Plus`>0)
;
select * from rcbill_my.clientstats
where region='PRASLIN' and
(`services` = 'All' or `services` like '%Voice%')
;
select * from rcbill_my.clientstats where region='Praslin';
*/ | true |
b1bda0eedb1afaecbb2c52c3b809458b06eb81e3 | SQL | EBISPOT/goci | /goci-core/goci-db-binding/src/main/resources/db/migration/V1.9.9_029__Entrez_gene_id_migration_pt2.sql | UTF-8 | 786 | 3.1875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /*
################################################################################
Retrospective fix to ensure merging happens after genomic context cleanup.
Designed for execution with Flyway database migrations tool.
author: Tony Burdett
date: March 9th 2015
version: 1.9.9.029 (pre 2.0)
################################################################################
*/
--------------------------------------------------------
-- Mods for Table GENE and GENOMIC_CONTEXT
--------------------------------------------------------
MERGE INTO GENE g
USING (SELECT DISTINCT GENE_ID, ENTREZ_GENE_ID FROM GENOMIC_CONTEXT) gc
ON (g.ID = gc.GENE_ID)
WHEN MATCHED THEN UPDATE SET g.ENTREZ_GENE_ID = gc.ENTREZ_GENE_ID;
ALTER TABLE GENOMIC_CONTEXT DROP COLUMN ENTREZ_GENE_ID;
| true |
b1a50f0e216bbb379e33c4aa402e1ecd1076f414 | SQL | postgres/postgres | /src/backend/catalog/information_schema.sql | UTF-8 | 114,880 | 4 | 4 | [
"PostgreSQL"
] | permissive | /*
* SQL Information Schema
* as defined in ISO/IEC 9075-11:2023
*
* Copyright (c) 2003-2023, PostgreSQL Global Development Group
*
* src/backend/catalog/information_schema.sql
*
* Note: this file is read in single-user -j mode, which means that the
* command terminator is semicolon-newline-newline; whenever the backend
* sees that, it stops and executes what it's got. If you write a lot of
* statements without empty lines between, they'll all get quoted to you
* in any error message about one of them, so don't do that. Also, you
* cannot write a semicolon immediately followed by an empty line in a
* string literal (including a function body!) or a multiline comment.
*/
/*
* Note: Generally, the definitions in this file should be ordered
* according to the clause numbers in the SQL standard, which is also the
* alphabetical order. In some cases it is convenient or necessary to
* define one information schema view by using another one; in that case,
* put the referencing view at the very end and leave a note where it
* should have been put.
*/
/*
* 6.2
* INFORMATION_SCHEMA schema
*/
CREATE SCHEMA information_schema;
GRANT USAGE ON SCHEMA information_schema TO PUBLIC;
SET search_path TO information_schema;
/*
* A few supporting functions first ...
*/
/* Expand any 1-D array into a set with integers 1..N */
CREATE FUNCTION _pg_expandarray(IN anyarray, OUT x anyelement, OUT n int)
RETURNS SETOF RECORD
LANGUAGE sql STRICT IMMUTABLE PARALLEL SAFE
AS 'select $1[s],
s operator(pg_catalog.-) pg_catalog.array_lower($1,1) operator(pg_catalog.+) 1
from pg_catalog.generate_series(pg_catalog.array_lower($1,1),
pg_catalog.array_upper($1,1),
1) as g(s)';
/* Given an index's OID and an underlying-table column number, return the
* column's position in the index (NULL if not there) */
CREATE FUNCTION _pg_index_position(oid, smallint) RETURNS int
LANGUAGE sql STRICT STABLE
BEGIN ATOMIC
SELECT (ss.a).n FROM
(SELECT information_schema._pg_expandarray(indkey) AS a
FROM pg_catalog.pg_index WHERE indexrelid = $1) ss
WHERE (ss.a).x = $2;
END;
CREATE FUNCTION _pg_truetypid(pg_attribute, pg_type) RETURNS oid
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN CASE WHEN $2.typtype = 'd' THEN $2.typbasetype ELSE $1.atttypid END;
CREATE FUNCTION _pg_truetypmod(pg_attribute, pg_type) RETURNS int4
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN CASE WHEN $2.typtype = 'd' THEN $2.typtypmod ELSE $1.atttypmod END;
-- these functions encapsulate knowledge about the encoding of typmod:
CREATE FUNCTION _pg_char_max_length(typid oid, typmod int4) RETURNS integer
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN
CASE WHEN $2 = -1 /* default typmod */
THEN null
WHEN $1 IN (1042, 1043) /* char, varchar */
THEN $2 - 4
WHEN $1 IN (1560, 1562) /* bit, varbit */
THEN $2
ELSE null
END;
CREATE FUNCTION _pg_char_octet_length(typid oid, typmod int4) RETURNS integer
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN
CASE WHEN $1 IN (25, 1042, 1043) /* text, char, varchar */
THEN CASE WHEN $2 = -1 /* default typmod */
THEN CAST(2^30 AS integer)
ELSE information_schema._pg_char_max_length($1, $2) *
pg_catalog.pg_encoding_max_length((SELECT encoding FROM pg_catalog.pg_database WHERE datname = pg_catalog.current_database()))
END
ELSE null
END;
CREATE FUNCTION _pg_numeric_precision(typid oid, typmod int4) RETURNS integer
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN
CASE $1
WHEN 21 /*int2*/ THEN 16
WHEN 23 /*int4*/ THEN 32
WHEN 20 /*int8*/ THEN 64
WHEN 1700 /*numeric*/ THEN
CASE WHEN $2 = -1
THEN null
ELSE (($2 - 4) >> 16) & 0xFFFF
END
WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/
WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/
ELSE null
END;
CREATE FUNCTION _pg_numeric_precision_radix(typid oid, typmod int4) RETURNS integer
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN
CASE WHEN $1 IN (21, 23, 20, 700, 701) THEN 2
WHEN $1 IN (1700) THEN 10
ELSE null
END;
CREATE FUNCTION _pg_numeric_scale(typid oid, typmod int4) RETURNS integer
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN
CASE WHEN $1 IN (21, 23, 20) THEN 0
WHEN $1 IN (1700) THEN
CASE WHEN $2 = -1
THEN null
ELSE ($2 - 4) & 0xFFFF
END
ELSE null
END;
CREATE FUNCTION _pg_datetime_precision(typid oid, typmod int4) RETURNS integer
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN
CASE WHEN $1 IN (1082) /* date */
THEN 0
WHEN $1 IN (1083, 1114, 1184, 1266) /* time, timestamp, same + tz */
THEN CASE WHEN $2 < 0 THEN 6 ELSE $2 END
WHEN $1 IN (1186) /* interval */
THEN CASE WHEN $2 < 0 OR $2 & 0xFFFF = 0xFFFF THEN 6 ELSE $2 & 0xFFFF END
ELSE null
END;
CREATE FUNCTION _pg_interval_type(typid oid, mod int4) RETURNS text
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
RETURNS NULL ON NULL INPUT
RETURN
CASE WHEN $1 IN (1186) /* interval */
THEN pg_catalog.upper(substring(pg_catalog.format_type($1, $2) similar 'interval[()0-9]* #"%#"' escape '#'))
ELSE null
END;
-- 6.3 INFORMATION_SCHEMA_CATALOG_NAME view appears later.
/*
* 6.4
* CARDINAL_NUMBER domain
*/
CREATE DOMAIN cardinal_number AS integer
CONSTRAINT cardinal_number_domain_check CHECK (value >= 0);
/*
* 6.5
* CHARACTER_DATA domain
*/
CREATE DOMAIN character_data AS character varying COLLATE "C";
/*
* 6.6
* SQL_IDENTIFIER domain
*/
CREATE DOMAIN sql_identifier AS name;
/*
* 6.3
* INFORMATION_SCHEMA_CATALOG_NAME view
*/
CREATE VIEW information_schema_catalog_name AS
SELECT CAST(current_database() AS sql_identifier) AS catalog_name;
GRANT SELECT ON information_schema_catalog_name TO PUBLIC;
/*
* 6.7
* TIME_STAMP domain
*/
CREATE DOMAIN time_stamp AS timestamp(2) with time zone
DEFAULT current_timestamp(2);
/*
* 6.8
* YES_OR_NO domain
*/
CREATE DOMAIN yes_or_no AS character varying(3) COLLATE "C"
CONSTRAINT yes_or_no_check CHECK (value IN ('YES', 'NO'));
-- 6.9 ADMINISTRABLE_ROLE_AUTHORIZATIONS view appears later.
/*
* 6.10
* APPLICABLE_ROLES view
*/
CREATE VIEW applicable_roles AS
SELECT CAST(a.rolname AS sql_identifier) AS grantee,
CAST(b.rolname AS sql_identifier) AS role_name,
CAST(CASE WHEN m.admin_option THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable
FROM (SELECT member, roleid, admin_option FROM pg_auth_members
-- This UNION could be UNION ALL, but UNION works even if we start
-- to allow explicit pg_database_owner membership.
UNION
SELECT datdba, pg_authid.oid, false
FROM pg_database, pg_authid
WHERE datname = current_database() AND rolname = 'pg_database_owner'
) m
JOIN pg_authid a ON (m.member = a.oid)
JOIN pg_authid b ON (m.roleid = b.oid)
WHERE pg_has_role(a.oid, 'USAGE');
GRANT SELECT ON applicable_roles TO PUBLIC;
/*
* 6.9
* ADMINISTRABLE_ROLE_AUTHORIZATIONS view
*/
CREATE VIEW administrable_role_authorizations AS
SELECT *
FROM applicable_roles
WHERE is_grantable = 'YES';
GRANT SELECT ON administrable_role_authorizations TO PUBLIC;
/*
* 6.11
* ASSERTIONS view
*/
-- feature not supported
/*
* 6.12
* ATTRIBUTES view
*/
CREATE VIEW attributes AS
SELECT CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(nc.nspname AS sql_identifier) AS udt_schema,
CAST(c.relname AS sql_identifier) AS udt_name,
CAST(a.attname AS sql_identifier) AS attribute_name,
CAST(a.attnum AS cardinal_number) AS ordinal_position,
CAST(pg_get_expr(ad.adbin, ad.adrelid) AS character_data) AS attribute_default,
CAST(CASE WHEN a.attnotnull OR (t.typtype = 'd' AND t.typnotnull) THEN 'NO' ELSE 'YES' END
AS yes_or_no)
AS is_nullable, -- This column was apparently removed between SQL:2003 and SQL:2008.
CAST(
CASE WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
WHEN nt.nspname = 'pg_catalog' THEN format_type(a.atttypid, null)
ELSE 'USER-DEFINED' END
AS character_data)
AS data_type,
CAST(
_pg_char_max_length(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS character_maximum_length,
CAST(
_pg_char_octet_length(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS character_octet_length,
CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(null AS sql_identifier) AS character_set_name,
CAST(CASE WHEN nco.nspname IS NOT NULL THEN current_database() END AS sql_identifier) AS collation_catalog,
CAST(nco.nspname AS sql_identifier) AS collation_schema,
CAST(co.collname AS sql_identifier) AS collation_name,
CAST(
_pg_numeric_precision(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS numeric_precision,
CAST(
_pg_numeric_precision_radix(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS numeric_precision_radix,
CAST(
_pg_numeric_scale(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS numeric_scale,
CAST(
_pg_datetime_precision(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS datetime_precision,
CAST(
_pg_interval_type(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS character_data)
AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
CAST(current_database() AS sql_identifier) AS attribute_udt_catalog,
CAST(nt.nspname AS sql_identifier) AS attribute_udt_schema,
CAST(t.typname AS sql_identifier) AS attribute_udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
CAST(null AS sql_identifier) AS scope_schema,
CAST(null AS sql_identifier) AS scope_name,
CAST(null AS cardinal_number) AS maximum_cardinality,
CAST(a.attnum AS sql_identifier) AS dtd_identifier,
CAST('NO' AS yes_or_no) AS is_derived_reference_attribute
FROM (pg_attribute a LEFT JOIN pg_attrdef ad ON attrelid = adrelid AND attnum = adnum)
JOIN (pg_class c JOIN pg_namespace nc ON (c.relnamespace = nc.oid)) ON a.attrelid = c.oid
JOIN (pg_type t JOIN pg_namespace nt ON (t.typnamespace = nt.oid)) ON a.atttypid = t.oid
LEFT JOIN (pg_collation co JOIN pg_namespace nco ON (co.collnamespace = nco.oid))
ON a.attcollation = co.oid AND (nco.nspname, co.collname) <> ('pg_catalog', 'default')
WHERE a.attnum > 0 AND NOT a.attisdropped
AND c.relkind IN ('c')
AND (pg_has_role(c.relowner, 'USAGE')
OR has_type_privilege(c.reltype, 'USAGE'));
GRANT SELECT ON attributes TO PUBLIC;
/*
* 6.13
* CHARACTER_SETS view
*/
CREATE VIEW character_sets AS
SELECT CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(getdatabaseencoding() AS sql_identifier) AS character_set_name,
CAST(CASE WHEN getdatabaseencoding() = 'UTF8' THEN 'UCS' ELSE getdatabaseencoding() END AS sql_identifier) AS character_repertoire,
CAST(getdatabaseencoding() AS sql_identifier) AS form_of_use,
CAST(current_database() AS sql_identifier) AS default_collate_catalog,
CAST(nc.nspname AS sql_identifier) AS default_collate_schema,
CAST(c.collname AS sql_identifier) AS default_collate_name
FROM pg_database d
LEFT JOIN (pg_collation c JOIN pg_namespace nc ON (c.collnamespace = nc.oid))
ON (datcollate = collcollate AND datctype = collctype)
WHERE d.datname = current_database()
ORDER BY char_length(c.collname) DESC, c.collname ASC -- prefer full/canonical name
LIMIT 1;
GRANT SELECT ON character_sets TO PUBLIC;
/*
* 6.14
* CHECK_CONSTRAINT_ROUTINE_USAGE view
*/
CREATE VIEW check_constraint_routine_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(nc.nspname AS sql_identifier) AS constraint_schema,
CAST(c.conname AS sql_identifier) AS constraint_name,
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(np.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name
FROM pg_namespace nc, pg_constraint c, pg_depend d, pg_proc p, pg_namespace np
WHERE nc.oid = c.connamespace
AND c.contype = 'c'
AND c.oid = d.objid
AND d.classid = 'pg_catalog.pg_constraint'::regclass
AND d.refobjid = p.oid
AND d.refclassid = 'pg_catalog.pg_proc'::regclass
AND p.pronamespace = np.oid
AND pg_has_role(p.proowner, 'USAGE');
GRANT SELECT ON check_constraint_routine_usage TO PUBLIC;
/*
* 6.15
* CHECK_CONSTRAINTS view
*/
CREATE VIEW check_constraints AS
SELECT CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(rs.nspname AS sql_identifier) AS constraint_schema,
CAST(con.conname AS sql_identifier) AS constraint_name,
CAST(substring(pg_get_constraintdef(con.oid) from 7) AS character_data)
AS check_clause
FROM pg_constraint con
LEFT OUTER JOIN pg_namespace rs ON (rs.oid = con.connamespace)
LEFT OUTER JOIN pg_class c ON (c.oid = con.conrelid)
LEFT OUTER JOIN pg_type t ON (t.oid = con.contypid)
WHERE pg_has_role(coalesce(c.relowner, t.typowner), 'USAGE')
AND con.contype = 'c'
UNION
-- not-null constraints
SELECT CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(n.nspname AS sql_identifier) AS constraint_schema,
CAST(CAST(n.oid AS text) || '_' || CAST(r.oid AS text) || '_' || CAST(a.attnum AS text) || '_not_null' AS sql_identifier) AS constraint_name, -- XXX
CAST(a.attname || ' IS NOT NULL' AS character_data)
AS check_clause
FROM pg_namespace n, pg_class r, pg_attribute a
WHERE n.oid = r.relnamespace
AND r.oid = a.attrelid
AND a.attnum > 0
AND NOT a.attisdropped
AND a.attnotnull
AND r.relkind IN ('r', 'p')
AND pg_has_role(r.relowner, 'USAGE');
GRANT SELECT ON check_constraints TO PUBLIC;
/*
* 6.16
* COLLATIONS view
*/
CREATE VIEW collations AS
SELECT CAST(current_database() AS sql_identifier) AS collation_catalog,
CAST(nc.nspname AS sql_identifier) AS collation_schema,
CAST(c.collname AS sql_identifier) AS collation_name,
CAST('NO PAD' AS character_data) AS pad_attribute
FROM pg_collation c, pg_namespace nc
WHERE c.collnamespace = nc.oid
AND collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database()));
GRANT SELECT ON collations TO PUBLIC;
/*
* 6.17
* COLLATION_CHARACTER_SET_APPLICABILITY view
*/
CREATE VIEW collation_character_set_applicability AS
SELECT CAST(current_database() AS sql_identifier) AS collation_catalog,
CAST(nc.nspname AS sql_identifier) AS collation_schema,
CAST(c.collname AS sql_identifier) AS collation_name,
CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(getdatabaseencoding() AS sql_identifier) AS character_set_name
FROM pg_collation c, pg_namespace nc
WHERE c.collnamespace = nc.oid
AND collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database()));
GRANT SELECT ON collation_character_set_applicability TO PUBLIC;
/*
* 6.18
* COLUMN_COLUMN_USAGE view
*/
CREATE VIEW column_column_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(n.nspname AS sql_identifier) AS table_schema,
CAST(c.relname AS sql_identifier) AS table_name,
CAST(ac.attname AS sql_identifier) AS column_name,
CAST(ad.attname AS sql_identifier) AS dependent_column
FROM pg_namespace n, pg_class c, pg_depend d,
pg_attribute ac, pg_attribute ad, pg_attrdef atd
WHERE n.oid = c.relnamespace
AND c.oid = ac.attrelid
AND c.oid = ad.attrelid
AND ac.attnum <> ad.attnum
AND ad.attrelid = atd.adrelid
AND ad.attnum = atd.adnum
AND d.classid = 'pg_catalog.pg_attrdef'::regclass
AND d.refclassid = 'pg_catalog.pg_class'::regclass
AND d.objid = atd.oid
AND d.refobjid = ac.attrelid
AND d.refobjsubid = ac.attnum
AND ad.attgenerated <> ''
AND pg_has_role(c.relowner, 'USAGE');
GRANT SELECT ON column_column_usage TO PUBLIC;
/*
* 6.19
* COLUMN_DOMAIN_USAGE view
*/
CREATE VIEW column_domain_usage AS
SELECT CAST(current_database() AS sql_identifier) AS domain_catalog,
CAST(nt.nspname AS sql_identifier) AS domain_schema,
CAST(t.typname AS sql_identifier) AS domain_name,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nc.nspname AS sql_identifier) AS table_schema,
CAST(c.relname AS sql_identifier) AS table_name,
CAST(a.attname AS sql_identifier) AS column_name
FROM pg_type t, pg_namespace nt, pg_class c, pg_namespace nc,
pg_attribute a
WHERE t.typnamespace = nt.oid
AND c.relnamespace = nc.oid
AND a.attrelid = c.oid
AND a.atttypid = t.oid
AND t.typtype = 'd'
AND c.relkind IN ('r', 'v', 'f', 'p')
AND a.attnum > 0
AND NOT a.attisdropped
AND pg_has_role(t.typowner, 'USAGE');
GRANT SELECT ON column_domain_usage TO PUBLIC;
/*
* 6.20
* COLUMN_PRIVILEGES
*/
CREATE VIEW column_privileges AS
SELECT CAST(u_grantor.rolname AS sql_identifier) AS grantor,
CAST(grantee.rolname AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nc.nspname AS sql_identifier) AS table_schema,
CAST(x.relname AS sql_identifier) AS table_name,
CAST(x.attname AS sql_identifier) AS column_name,
CAST(x.prtype AS character_data) AS privilege_type,
CAST(
CASE WHEN
-- object owner always has grant options
pg_has_role(x.grantee, x.relowner, 'USAGE')
OR x.grantable
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable
FROM (
SELECT pr_c.grantor,
pr_c.grantee,
attname,
relname,
relnamespace,
pr_c.prtype,
pr_c.grantable,
pr_c.relowner
FROM (SELECT oid, relname, relnamespace, relowner, (aclexplode(coalesce(relacl, acldefault('r', relowner)))).*
FROM pg_class
WHERE relkind IN ('r', 'v', 'f', 'p')
) pr_c (oid, relname, relnamespace, relowner, grantor, grantee, prtype, grantable),
pg_attribute a
WHERE a.attrelid = pr_c.oid
AND a.attnum > 0
AND NOT a.attisdropped
UNION
SELECT pr_a.grantor,
pr_a.grantee,
attname,
relname,
relnamespace,
pr_a.prtype,
pr_a.grantable,
c.relowner
FROM (SELECT attrelid, attname, (aclexplode(coalesce(attacl, acldefault('c', relowner)))).*
FROM pg_attribute a JOIN pg_class cc ON (a.attrelid = cc.oid)
WHERE attnum > 0
AND NOT attisdropped
) pr_a (attrelid, attname, grantor, grantee, prtype, grantable),
pg_class c
WHERE pr_a.attrelid = c.oid
AND relkind IN ('r', 'v', 'f', 'p')
) x,
pg_namespace nc,
pg_authid u_grantor,
(
SELECT oid, rolname FROM pg_authid
UNION ALL
SELECT 0::oid, 'PUBLIC'
) AS grantee (oid, rolname)
WHERE x.relnamespace = nc.oid
AND x.grantee = grantee.oid
AND x.grantor = u_grantor.oid
AND x.prtype IN ('INSERT', 'SELECT', 'UPDATE', 'REFERENCES')
AND (pg_has_role(u_grantor.oid, 'USAGE')
OR pg_has_role(grantee.oid, 'USAGE')
OR grantee.rolname = 'PUBLIC');
GRANT SELECT ON column_privileges TO PUBLIC;
/*
* 6.21
* COLUMN_UDT_USAGE view
*/
CREATE VIEW column_udt_usage AS
SELECT CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(coalesce(nbt.nspname, nt.nspname) AS sql_identifier) AS udt_schema,
CAST(coalesce(bt.typname, t.typname) AS sql_identifier) AS udt_name,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nc.nspname AS sql_identifier) AS table_schema,
CAST(c.relname AS sql_identifier) AS table_name,
CAST(a.attname AS sql_identifier) AS column_name
FROM pg_attribute a, pg_class c, pg_namespace nc,
(pg_type t JOIN pg_namespace nt ON (t.typnamespace = nt.oid))
LEFT JOIN (pg_type bt JOIN pg_namespace nbt ON (bt.typnamespace = nbt.oid))
ON (t.typtype = 'd' AND t.typbasetype = bt.oid)
WHERE a.attrelid = c.oid
AND a.atttypid = t.oid
AND nc.oid = c.relnamespace
AND a.attnum > 0 AND NOT a.attisdropped
AND c.relkind in ('r', 'v', 'f', 'p')
AND pg_has_role(coalesce(bt.typowner, t.typowner), 'USAGE');
GRANT SELECT ON column_udt_usage TO PUBLIC;
/*
* 6.22
* COLUMNS view
*/
CREATE VIEW columns AS
SELECT CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nc.nspname AS sql_identifier) AS table_schema,
CAST(c.relname AS sql_identifier) AS table_name,
CAST(a.attname AS sql_identifier) AS column_name,
CAST(a.attnum AS cardinal_number) AS ordinal_position,
CAST(CASE WHEN a.attgenerated = '' THEN pg_get_expr(ad.adbin, ad.adrelid) END AS character_data) AS column_default,
CAST(CASE WHEN a.attnotnull OR (t.typtype = 'd' AND t.typnotnull) THEN 'NO' ELSE 'YES' END
AS yes_or_no)
AS is_nullable,
CAST(
CASE WHEN t.typtype = 'd' THEN
CASE WHEN bt.typelem <> 0 AND bt.typlen = -1 THEN 'ARRAY'
WHEN nbt.nspname = 'pg_catalog' THEN format_type(t.typbasetype, null)
ELSE 'USER-DEFINED' END
ELSE
CASE WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
WHEN nt.nspname = 'pg_catalog' THEN format_type(a.atttypid, null)
ELSE 'USER-DEFINED' END
END
AS character_data)
AS data_type,
CAST(
_pg_char_max_length(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS character_maximum_length,
CAST(
_pg_char_octet_length(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS character_octet_length,
CAST(
_pg_numeric_precision(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS numeric_precision,
CAST(
_pg_numeric_precision_radix(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS numeric_precision_radix,
CAST(
_pg_numeric_scale(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS numeric_scale,
CAST(
_pg_datetime_precision(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS cardinal_number)
AS datetime_precision,
CAST(
_pg_interval_type(_pg_truetypid(a, t), _pg_truetypmod(a, t))
AS character_data)
AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(null AS sql_identifier) AS character_set_name,
CAST(CASE WHEN nco.nspname IS NOT NULL THEN current_database() END AS sql_identifier) AS collation_catalog,
CAST(nco.nspname AS sql_identifier) AS collation_schema,
CAST(co.collname AS sql_identifier) AS collation_name,
CAST(CASE WHEN t.typtype = 'd' THEN current_database() ELSE null END
AS sql_identifier) AS domain_catalog,
CAST(CASE WHEN t.typtype = 'd' THEN nt.nspname ELSE null END
AS sql_identifier) AS domain_schema,
CAST(CASE WHEN t.typtype = 'd' THEN t.typname ELSE null END
AS sql_identifier) AS domain_name,
CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(coalesce(nbt.nspname, nt.nspname) AS sql_identifier) AS udt_schema,
CAST(coalesce(bt.typname, t.typname) AS sql_identifier) AS udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
CAST(null AS sql_identifier) AS scope_schema,
CAST(null AS sql_identifier) AS scope_name,
CAST(null AS cardinal_number) AS maximum_cardinality,
CAST(a.attnum AS sql_identifier) AS dtd_identifier,
CAST('NO' AS yes_or_no) AS is_self_referencing,
CAST(CASE WHEN a.attidentity IN ('a', 'd') THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_identity,
CAST(CASE a.attidentity WHEN 'a' THEN 'ALWAYS' WHEN 'd' THEN 'BY DEFAULT' END AS character_data) AS identity_generation,
CAST(seq.seqstart AS character_data) AS identity_start,
CAST(seq.seqincrement AS character_data) AS identity_increment,
CAST(seq.seqmax AS character_data) AS identity_maximum,
CAST(seq.seqmin AS character_data) AS identity_minimum,
CAST(CASE WHEN seq.seqcycle THEN 'YES' ELSE 'NO' END AS yes_or_no) AS identity_cycle,
CAST(CASE WHEN a.attgenerated <> '' THEN 'ALWAYS' ELSE 'NEVER' END AS character_data) AS is_generated,
CAST(CASE WHEN a.attgenerated <> '' THEN pg_get_expr(ad.adbin, ad.adrelid) END AS character_data) AS generation_expression,
CAST(CASE WHEN c.relkind IN ('r', 'p') OR
(c.relkind IN ('v', 'f') AND
pg_column_is_updatable(c.oid, a.attnum, false))
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_updatable
FROM (pg_attribute a LEFT JOIN pg_attrdef ad ON attrelid = adrelid AND attnum = adnum)
JOIN (pg_class c JOIN pg_namespace nc ON (c.relnamespace = nc.oid)) ON a.attrelid = c.oid
JOIN (pg_type t JOIN pg_namespace nt ON (t.typnamespace = nt.oid)) ON a.atttypid = t.oid
LEFT JOIN (pg_type bt JOIN pg_namespace nbt ON (bt.typnamespace = nbt.oid))
ON (t.typtype = 'd' AND t.typbasetype = bt.oid)
LEFT JOIN (pg_collation co JOIN pg_namespace nco ON (co.collnamespace = nco.oid))
ON a.attcollation = co.oid AND (nco.nspname, co.collname) <> ('pg_catalog', 'default')
LEFT JOIN (pg_depend dep JOIN pg_sequence seq ON (dep.classid = 'pg_class'::regclass AND dep.objid = seq.seqrelid AND dep.deptype = 'i'))
ON (dep.refclassid = 'pg_class'::regclass AND dep.refobjid = c.oid AND dep.refobjsubid = a.attnum)
WHERE (NOT pg_is_other_temp_schema(nc.oid))
AND a.attnum > 0 AND NOT a.attisdropped
AND c.relkind IN ('r', 'v', 'f', 'p')
AND (pg_has_role(c.relowner, 'USAGE')
OR has_column_privilege(c.oid, a.attnum,
'SELECT, INSERT, UPDATE, REFERENCES'));
GRANT SELECT ON columns TO PUBLIC;
/*
* 6.23
* CONSTRAINT_COLUMN_USAGE view
*/
CREATE VIEW constraint_column_usage AS
SELECT CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(tblschema AS sql_identifier) AS table_schema,
CAST(tblname AS sql_identifier) AS table_name,
CAST(colname AS sql_identifier) AS column_name,
CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(cstrschema AS sql_identifier) AS constraint_schema,
CAST(cstrname AS sql_identifier) AS constraint_name
FROM (
/* check constraints */
SELECT DISTINCT nr.nspname, r.relname, r.relowner, a.attname, nc.nspname, c.conname
FROM pg_namespace nr, pg_class r, pg_attribute a, pg_depend d, pg_namespace nc, pg_constraint c
WHERE nr.oid = r.relnamespace
AND r.oid = a.attrelid
AND d.refclassid = 'pg_catalog.pg_class'::regclass
AND d.refobjid = r.oid
AND d.refobjsubid = a.attnum
AND d.classid = 'pg_catalog.pg_constraint'::regclass
AND d.objid = c.oid
AND c.connamespace = nc.oid
AND c.contype = 'c'
AND r.relkind IN ('r', 'p')
AND NOT a.attisdropped
UNION ALL
/* unique/primary key/foreign key constraints */
SELECT nr.nspname, r.relname, r.relowner, a.attname, nc.nspname, c.conname
FROM pg_namespace nr, pg_class r, pg_attribute a, pg_namespace nc,
pg_constraint c
WHERE nr.oid = r.relnamespace
AND r.oid = a.attrelid
AND nc.oid = c.connamespace
AND r.oid = CASE c.contype WHEN 'f' THEN c.confrelid ELSE c.conrelid END
AND a.attnum = ANY (CASE c.contype WHEN 'f' THEN c.confkey ELSE c.conkey END)
AND NOT a.attisdropped
AND c.contype IN ('p', 'u', 'f')
AND r.relkind IN ('r', 'p')
) AS x (tblschema, tblname, tblowner, colname, cstrschema, cstrname)
WHERE pg_has_role(x.tblowner, 'USAGE');
GRANT SELECT ON constraint_column_usage TO PUBLIC;
/*
* 6.24
* CONSTRAINT_PERIOD_USAGE view
*/
-- feature not supported
/*
* 6.25
* CONSTRAINT_TABLE_USAGE view
*/
CREATE VIEW constraint_table_usage AS
SELECT CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nr.nspname AS sql_identifier) AS table_schema,
CAST(r.relname AS sql_identifier) AS table_name,
CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(nc.nspname AS sql_identifier) AS constraint_schema,
CAST(c.conname AS sql_identifier) AS constraint_name
FROM pg_constraint c, pg_namespace nc,
pg_class r, pg_namespace nr
WHERE c.connamespace = nc.oid AND r.relnamespace = nr.oid
AND ( (c.contype = 'f' AND c.confrelid = r.oid)
OR (c.contype IN ('p', 'u') AND c.conrelid = r.oid) )
AND r.relkind IN ('r', 'p')
AND pg_has_role(r.relowner, 'USAGE');
GRANT SELECT ON constraint_table_usage TO PUBLIC;
-- 6.26 DATA_TYPE_PRIVILEGES view appears later.
/*
* 6.27
* DIRECT_SUPERTABLES view
*/
-- feature not supported
/*
* 6.28
* DIRECT_SUPERTYPES view
*/
-- feature not supported
/*
* 6.29
* DOMAIN_CONSTRAINTS view
*/
CREATE VIEW domain_constraints AS
SELECT CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(rs.nspname AS sql_identifier) AS constraint_schema,
CAST(con.conname AS sql_identifier) AS constraint_name,
CAST(current_database() AS sql_identifier) AS domain_catalog,
CAST(n.nspname AS sql_identifier) AS domain_schema,
CAST(t.typname AS sql_identifier) AS domain_name,
CAST(CASE WHEN condeferrable THEN 'YES' ELSE 'NO' END
AS yes_or_no) AS is_deferrable,
CAST(CASE WHEN condeferred THEN 'YES' ELSE 'NO' END
AS yes_or_no) AS initially_deferred
FROM pg_namespace rs, pg_namespace n, pg_constraint con, pg_type t
WHERE rs.oid = con.connamespace
AND n.oid = t.typnamespace
AND t.oid = con.contypid
AND (pg_has_role(t.typowner, 'USAGE')
OR has_type_privilege(t.oid, 'USAGE'));
GRANT SELECT ON domain_constraints TO PUBLIC;
/*
* DOMAIN_UDT_USAGE view
* apparently removed in SQL:2003
*/
CREATE VIEW domain_udt_usage AS
SELECT CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(nbt.nspname AS sql_identifier) AS udt_schema,
CAST(bt.typname AS sql_identifier) AS udt_name,
CAST(current_database() AS sql_identifier) AS domain_catalog,
CAST(nt.nspname AS sql_identifier) AS domain_schema,
CAST(t.typname AS sql_identifier) AS domain_name
FROM pg_type t, pg_namespace nt,
pg_type bt, pg_namespace nbt
WHERE t.typnamespace = nt.oid
AND t.typbasetype = bt.oid
AND bt.typnamespace = nbt.oid
AND t.typtype = 'd'
AND pg_has_role(bt.typowner, 'USAGE');
GRANT SELECT ON domain_udt_usage TO PUBLIC;
/*
* 6.30
* DOMAINS view
*/
CREATE VIEW domains AS
SELECT CAST(current_database() AS sql_identifier) AS domain_catalog,
CAST(nt.nspname AS sql_identifier) AS domain_schema,
CAST(t.typname AS sql_identifier) AS domain_name,
CAST(
CASE WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
WHEN nbt.nspname = 'pg_catalog' THEN format_type(t.typbasetype, null)
ELSE 'USER-DEFINED' END
AS character_data)
AS data_type,
CAST(
_pg_char_max_length(t.typbasetype, t.typtypmod)
AS cardinal_number)
AS character_maximum_length,
CAST(
_pg_char_octet_length(t.typbasetype, t.typtypmod)
AS cardinal_number)
AS character_octet_length,
CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(null AS sql_identifier) AS character_set_name,
CAST(CASE WHEN nco.nspname IS NOT NULL THEN current_database() END AS sql_identifier) AS collation_catalog,
CAST(nco.nspname AS sql_identifier) AS collation_schema,
CAST(co.collname AS sql_identifier) AS collation_name,
CAST(
_pg_numeric_precision(t.typbasetype, t.typtypmod)
AS cardinal_number)
AS numeric_precision,
CAST(
_pg_numeric_precision_radix(t.typbasetype, t.typtypmod)
AS cardinal_number)
AS numeric_precision_radix,
CAST(
_pg_numeric_scale(t.typbasetype, t.typtypmod)
AS cardinal_number)
AS numeric_scale,
CAST(
_pg_datetime_precision(t.typbasetype, t.typtypmod)
AS cardinal_number)
AS datetime_precision,
CAST(
_pg_interval_type(t.typbasetype, t.typtypmod)
AS character_data)
AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
CAST(t.typdefault AS character_data) AS domain_default,
CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(nbt.nspname AS sql_identifier) AS udt_schema,
CAST(bt.typname AS sql_identifier) AS udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
CAST(null AS sql_identifier) AS scope_schema,
CAST(null AS sql_identifier) AS scope_name,
CAST(null AS cardinal_number) AS maximum_cardinality,
CAST(1 AS sql_identifier) AS dtd_identifier
FROM (pg_type t JOIN pg_namespace nt ON t.typnamespace = nt.oid)
JOIN (pg_type bt JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid)
ON (t.typbasetype = bt.oid AND t.typtype = 'd')
LEFT JOIN (pg_collation co JOIN pg_namespace nco ON (co.collnamespace = nco.oid))
ON t.typcollation = co.oid AND (nco.nspname, co.collname) <> ('pg_catalog', 'default')
WHERE (pg_has_role(t.typowner, 'USAGE')
OR has_type_privilege(t.oid, 'USAGE'));
GRANT SELECT ON domains TO PUBLIC;
-- 6.31 ELEMENT_TYPES view appears later.
/*
* 6.32
* ENABLED_ROLES view
*/
CREATE VIEW enabled_roles AS
SELECT CAST(a.rolname AS sql_identifier) AS role_name
FROM pg_authid a
WHERE pg_has_role(a.oid, 'USAGE');
GRANT SELECT ON enabled_roles TO PUBLIC;
/*
* 6.33
* FIELDS view
*/
-- feature not supported
/*
* 6.34
* KEY_COLUMN_USAGE view
*/
CREATE VIEW key_column_usage AS
SELECT CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(nc_nspname AS sql_identifier) AS constraint_schema,
CAST(conname AS sql_identifier) AS constraint_name,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nr_nspname AS sql_identifier) AS table_schema,
CAST(relname AS sql_identifier) AS table_name,
CAST(a.attname AS sql_identifier) AS column_name,
CAST((ss.x).n AS cardinal_number) AS ordinal_position,
CAST(CASE WHEN contype = 'f' THEN
_pg_index_position(ss.conindid, ss.confkey[(ss.x).n])
ELSE NULL
END AS cardinal_number)
AS position_in_unique_constraint
FROM pg_attribute a,
(SELECT r.oid AS roid, r.relname, r.relowner,
nc.nspname AS nc_nspname, nr.nspname AS nr_nspname,
c.oid AS coid, c.conname, c.contype, c.conindid,
c.confkey, c.confrelid,
_pg_expandarray(c.conkey) AS x
FROM pg_namespace nr, pg_class r, pg_namespace nc,
pg_constraint c
WHERE nr.oid = r.relnamespace
AND r.oid = c.conrelid
AND nc.oid = c.connamespace
AND c.contype IN ('p', 'u', 'f')
AND r.relkind IN ('r', 'p')
AND (NOT pg_is_other_temp_schema(nr.oid)) ) AS ss
WHERE ss.roid = a.attrelid
AND a.attnum = (ss.x).x
AND NOT a.attisdropped
AND (pg_has_role(relowner, 'USAGE')
OR has_column_privilege(roid, a.attnum,
'SELECT, INSERT, UPDATE, REFERENCES'));
GRANT SELECT ON key_column_usage TO PUBLIC;
/*
* 6.35
* KEY_PERIOD_USAGE view
*/
-- feature not supported
/*
* 6.36
* METHOD_SPECIFICATION_PARAMETERS view
*/
-- feature not supported
/*
* 6.37
* METHOD_SPECIFICATIONS view
*/
-- feature not supported
/*
* 6.38
* PARAMETERS view
*/
CREATE VIEW parameters AS
SELECT CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(n_nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(proname, p_oid) AS sql_identifier) AS specific_name,
CAST((ss.x).n AS cardinal_number) AS ordinal_position,
CAST(
CASE WHEN proargmodes IS NULL THEN 'IN'
WHEN proargmodes[(ss.x).n] = 'i' THEN 'IN'
WHEN proargmodes[(ss.x).n] = 'o' THEN 'OUT'
WHEN proargmodes[(ss.x).n] = 'b' THEN 'INOUT'
WHEN proargmodes[(ss.x).n] = 'v' THEN 'IN'
WHEN proargmodes[(ss.x).n] = 't' THEN 'OUT'
END AS character_data) AS parameter_mode,
CAST('NO' AS yes_or_no) AS is_result,
CAST('NO' AS yes_or_no) AS as_locator,
CAST(NULLIF(proargnames[(ss.x).n], '') AS sql_identifier) AS parameter_name,
CAST(
CASE WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
WHEN nt.nspname = 'pg_catalog' THEN format_type(t.oid, null)
ELSE 'USER-DEFINED' END AS character_data)
AS data_type,
CAST(null AS cardinal_number) AS character_maximum_length,
CAST(null AS cardinal_number) AS character_octet_length,
CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(null AS sql_identifier) AS character_set_name,
CAST(null AS sql_identifier) AS collation_catalog,
CAST(null AS sql_identifier) AS collation_schema,
CAST(null AS sql_identifier) AS collation_name,
CAST(null AS cardinal_number) AS numeric_precision,
CAST(null AS cardinal_number) AS numeric_precision_radix,
CAST(null AS cardinal_number) AS numeric_scale,
CAST(null AS cardinal_number) AS datetime_precision,
CAST(null AS character_data) AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(nt.nspname AS sql_identifier) AS udt_schema,
CAST(t.typname AS sql_identifier) AS udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
CAST(null AS sql_identifier) AS scope_schema,
CAST(null AS sql_identifier) AS scope_name,
CAST(null AS cardinal_number) AS maximum_cardinality,
CAST((ss.x).n AS sql_identifier) AS dtd_identifier,
CAST(
CASE WHEN pg_has_role(proowner, 'USAGE')
THEN pg_get_function_arg_default(p_oid, (ss.x).n)
ELSE NULL END
AS character_data) AS parameter_default
FROM pg_type t, pg_namespace nt,
(SELECT n.nspname AS n_nspname, p.proname, p.oid AS p_oid, p.proowner,
p.proargnames, p.proargmodes,
_pg_expandarray(coalesce(p.proallargtypes, p.proargtypes::oid[])) AS x
FROM pg_namespace n, pg_proc p
WHERE n.oid = p.pronamespace
AND (pg_has_role(p.proowner, 'USAGE') OR
has_function_privilege(p.oid, 'EXECUTE'))) AS ss
WHERE t.oid = (ss.x).x AND t.typnamespace = nt.oid;
GRANT SELECT ON parameters TO PUBLIC;
/*
* 6.39
* PERIODS view
*/
-- feature not supported
/*
* 6.40
* PRIVATE_PARAMETERS view
*/
-- feature not supported
/*
* 6.41
* REFERENCED_TYPES view
*/
-- feature not supported
/*
* 6.42
* REFERENTIAL_CONSTRAINTS view
*/
CREATE VIEW referential_constraints AS
SELECT CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(ncon.nspname AS sql_identifier) AS constraint_schema,
CAST(con.conname AS sql_identifier) AS constraint_name,
CAST(
CASE WHEN npkc.nspname IS NULL THEN NULL
ELSE current_database() END
AS sql_identifier) AS unique_constraint_catalog,
CAST(npkc.nspname AS sql_identifier) AS unique_constraint_schema,
CAST(pkc.conname AS sql_identifier) AS unique_constraint_name,
CAST(
CASE con.confmatchtype WHEN 'f' THEN 'FULL'
WHEN 'p' THEN 'PARTIAL'
WHEN 's' THEN 'NONE' END
AS character_data) AS match_option,
CAST(
CASE con.confupdtype WHEN 'c' THEN 'CASCADE'
WHEN 'n' THEN 'SET NULL'
WHEN 'd' THEN 'SET DEFAULT'
WHEN 'r' THEN 'RESTRICT'
WHEN 'a' THEN 'NO ACTION' END
AS character_data) AS update_rule,
CAST(
CASE con.confdeltype WHEN 'c' THEN 'CASCADE'
WHEN 'n' THEN 'SET NULL'
WHEN 'd' THEN 'SET DEFAULT'
WHEN 'r' THEN 'RESTRICT'
WHEN 'a' THEN 'NO ACTION' END
AS character_data) AS delete_rule
FROM (pg_namespace ncon
INNER JOIN pg_constraint con ON ncon.oid = con.connamespace
INNER JOIN pg_class c ON con.conrelid = c.oid AND con.contype = 'f')
LEFT JOIN pg_depend d1 -- find constraint's dependency on an index
ON d1.objid = con.oid AND d1.classid = 'pg_constraint'::regclass
AND d1.refclassid = 'pg_class'::regclass AND d1.refobjsubid = 0
LEFT JOIN pg_depend d2 -- find pkey/unique constraint for that index
ON d2.refclassid = 'pg_constraint'::regclass
AND d2.classid = 'pg_class'::regclass
AND d2.objid = d1.refobjid AND d2.objsubid = 0
AND d2.deptype = 'i'
LEFT JOIN pg_constraint pkc ON pkc.oid = d2.refobjid
AND pkc.contype IN ('p', 'u')
AND pkc.conrelid = con.confrelid
LEFT JOIN pg_namespace npkc ON pkc.connamespace = npkc.oid
WHERE pg_has_role(c.relowner, 'USAGE')
-- SELECT privilege omitted, per SQL standard
OR has_table_privilege(c.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER')
OR has_any_column_privilege(c.oid, 'INSERT, UPDATE, REFERENCES') ;
GRANT SELECT ON referential_constraints TO PUBLIC;
/*
* 6.43
* ROLE_COLUMN_GRANTS view
*/
CREATE VIEW role_column_grants AS
SELECT grantor,
grantee,
table_catalog,
table_schema,
table_name,
column_name,
privilege_type,
is_grantable
FROM column_privileges
WHERE grantor IN (SELECT role_name FROM enabled_roles)
OR grantee IN (SELECT role_name FROM enabled_roles);
GRANT SELECT ON role_column_grants TO PUBLIC;
-- 6.44 ROLE_ROUTINE_GRANTS view is based on 6.51 ROUTINE_PRIVILEGES and is defined there instead.
-- 6.45 ROLE_TABLE_GRANTS view is based on 6.64 TABLE_PRIVILEGES and is defined there instead.
/*
* 6.46
* ROLE_TABLE_METHOD_GRANTS view
*/
-- feature not supported
-- 6.47 ROLE_USAGE_GRANTS view is based on 6.76 USAGE_PRIVILEGES and is defined there instead.
-- 6.48 ROLE_UDT_GRANTS view is based on 6.75 UDT_PRIVILEGES and is defined there instead.
/*
* 6.49
* ROUTINE_COLUMN_USAGE view
*/
CREATE VIEW routine_column_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(np.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name,
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(np.nspname AS sql_identifier) AS routine_schema,
CAST(p.proname AS sql_identifier) AS routine_name,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nt.nspname AS sql_identifier) AS table_schema,
CAST(t.relname AS sql_identifier) AS table_name,
CAST(a.attname AS sql_identifier) AS column_name
FROM pg_namespace np, pg_proc p, pg_depend d,
pg_class t, pg_namespace nt, pg_attribute a
WHERE np.oid = p.pronamespace
AND p.oid = d.objid
AND d.classid = 'pg_catalog.pg_proc'::regclass
AND d.refobjid = t.oid
AND d.refclassid = 'pg_catalog.pg_class'::regclass
AND t.relnamespace = nt.oid
AND t.relkind IN ('r', 'v', 'f', 'p')
AND t.oid = a.attrelid
AND d.refobjsubid = a.attnum
AND pg_has_role(t.relowner, 'USAGE');
GRANT SELECT ON routine_column_usage TO PUBLIC;
/*
* 6.50
* ROUTINE_PERIOD_USAGE view
*/
-- feature not supported
/*
* 6.51
* ROUTINE_PRIVILEGES view
*/
CREATE VIEW routine_privileges AS
SELECT CAST(u_grantor.rolname AS sql_identifier) AS grantor,
CAST(grantee.rolname AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(n.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name,
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(n.nspname AS sql_identifier) AS routine_schema,
CAST(p.proname AS sql_identifier) AS routine_name,
CAST('EXECUTE' AS character_data) AS privilege_type,
CAST(
CASE WHEN
-- object owner always has grant options
pg_has_role(grantee.oid, p.proowner, 'USAGE')
OR p.grantable
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable
FROM (
SELECT oid, proname, proowner, pronamespace, (aclexplode(coalesce(proacl, acldefault('f', proowner)))).* FROM pg_proc
) p (oid, proname, proowner, pronamespace, grantor, grantee, prtype, grantable),
pg_namespace n,
pg_authid u_grantor,
(
SELECT oid, rolname FROM pg_authid
UNION ALL
SELECT 0::oid, 'PUBLIC'
) AS grantee (oid, rolname)
WHERE p.pronamespace = n.oid
AND grantee.oid = p.grantee
AND u_grantor.oid = p.grantor
AND p.prtype IN ('EXECUTE')
AND (pg_has_role(u_grantor.oid, 'USAGE')
OR pg_has_role(grantee.oid, 'USAGE')
OR grantee.rolname = 'PUBLIC');
GRANT SELECT ON routine_privileges TO PUBLIC;
/*
* 6.43
* ROLE_ROUTINE_GRANTS view
*/
CREATE VIEW role_routine_grants AS
SELECT grantor,
grantee,
specific_catalog,
specific_schema,
specific_name,
routine_catalog,
routine_schema,
routine_name,
privilege_type,
is_grantable
FROM routine_privileges
WHERE grantor IN (SELECT role_name FROM enabled_roles)
OR grantee IN (SELECT role_name FROM enabled_roles);
GRANT SELECT ON role_routine_grants TO PUBLIC;
/*
* 6.52
* ROUTINE_ROUTINE_USAGE view
*/
CREATE VIEW routine_routine_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(np.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name,
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(np1.nspname AS sql_identifier) AS routine_schema,
CAST(nameconcatoid(p1.proname, p1.oid) AS sql_identifier) AS routine_name
FROM pg_namespace np, pg_proc p, pg_depend d,
pg_proc p1, pg_namespace np1
WHERE np.oid = p.pronamespace
AND p.oid = d.objid
AND d.classid = 'pg_catalog.pg_proc'::regclass
AND d.refobjid = p1.oid
AND d.refclassid = 'pg_catalog.pg_proc'::regclass
AND p1.pronamespace = np1.oid
AND p.prokind IN ('f', 'p') AND p1.prokind IN ('f', 'p')
AND pg_has_role(p1.proowner, 'USAGE');
GRANT SELECT ON routine_routine_usage TO PUBLIC;
/*
* 6.53
* ROUTINE_SEQUENCE_USAGE view
*/
CREATE VIEW routine_sequence_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(np.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name,
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(np.nspname AS sql_identifier) AS routine_schema,
CAST(p.proname AS sql_identifier) AS routine_name,
CAST(current_database() AS sql_identifier) AS sequence_catalog,
CAST(ns.nspname AS sql_identifier) AS sequence_schema,
CAST(s.relname AS sql_identifier) AS sequence_name
FROM pg_namespace np, pg_proc p, pg_depend d,
pg_class s, pg_namespace ns
WHERE np.oid = p.pronamespace
AND p.oid = d.objid
AND d.classid = 'pg_catalog.pg_proc'::regclass
AND d.refobjid = s.oid
AND d.refclassid = 'pg_catalog.pg_class'::regclass
AND s.relnamespace = ns.oid
AND s.relkind = 'S'
AND pg_has_role(s.relowner, 'USAGE');
GRANT SELECT ON routine_sequence_usage TO PUBLIC;
/*
* 6.54
* ROUTINE_TABLE_USAGE view
*/
CREATE VIEW routine_table_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(np.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name,
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(np.nspname AS sql_identifier) AS routine_schema,
CAST(p.proname AS sql_identifier) AS routine_name,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nt.nspname AS sql_identifier) AS table_schema,
CAST(t.relname AS sql_identifier) AS table_name
FROM pg_namespace np, pg_proc p, pg_depend d,
pg_class t, pg_namespace nt
WHERE np.oid = p.pronamespace
AND p.oid = d.objid
AND d.classid = 'pg_catalog.pg_proc'::regclass
AND d.refobjid = t.oid
AND d.refclassid = 'pg_catalog.pg_class'::regclass
AND t.relnamespace = nt.oid
AND t.relkind IN ('r', 'v', 'f', 'p')
AND pg_has_role(t.relowner, 'USAGE');
GRANT SELECT ON routine_table_usage TO PUBLIC;
/*
* 6.55
* ROUTINES view
*/
CREATE VIEW routines AS
SELECT CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(n.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name,
CAST(current_database() AS sql_identifier) AS routine_catalog,
CAST(n.nspname AS sql_identifier) AS routine_schema,
CAST(p.proname AS sql_identifier) AS routine_name,
CAST(CASE p.prokind WHEN 'f' THEN 'FUNCTION' WHEN 'p' THEN 'PROCEDURE' END
AS character_data) AS routine_type,
CAST(null AS sql_identifier) AS module_catalog,
CAST(null AS sql_identifier) AS module_schema,
CAST(null AS sql_identifier) AS module_name,
CAST(null AS sql_identifier) AS udt_catalog,
CAST(null AS sql_identifier) AS udt_schema,
CAST(null AS sql_identifier) AS udt_name,
CAST(
CASE WHEN p.prokind = 'p' THEN NULL
WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
WHEN nt.nspname = 'pg_catalog' THEN format_type(t.oid, null)
ELSE 'USER-DEFINED' END AS character_data)
AS data_type,
CAST(null AS cardinal_number) AS character_maximum_length,
CAST(null AS cardinal_number) AS character_octet_length,
CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(null AS sql_identifier) AS character_set_name,
CAST(null AS sql_identifier) AS collation_catalog,
CAST(null AS sql_identifier) AS collation_schema,
CAST(null AS sql_identifier) AS collation_name,
CAST(null AS cardinal_number) AS numeric_precision,
CAST(null AS cardinal_number) AS numeric_precision_radix,
CAST(null AS cardinal_number) AS numeric_scale,
CAST(null AS cardinal_number) AS datetime_precision,
CAST(null AS character_data) AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
CAST(CASE WHEN nt.nspname IS NOT NULL THEN current_database() END AS sql_identifier) AS type_udt_catalog,
CAST(nt.nspname AS sql_identifier) AS type_udt_schema,
CAST(t.typname AS sql_identifier) AS type_udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
CAST(null AS sql_identifier) AS scope_schema,
CAST(null AS sql_identifier) AS scope_name,
CAST(null AS cardinal_number) AS maximum_cardinality,
CAST(CASE WHEN p.prokind <> 'p' THEN 0 END AS sql_identifier) AS dtd_identifier,
CAST(CASE WHEN l.lanname = 'sql' THEN 'SQL' ELSE 'EXTERNAL' END AS character_data)
AS routine_body,
CAST(
CASE WHEN pg_has_role(p.proowner, 'USAGE') THEN p.prosrc ELSE null END
AS character_data) AS routine_definition,
CAST(
CASE WHEN l.lanname = 'c' THEN p.prosrc ELSE null END
AS character_data) AS external_name,
CAST(upper(l.lanname) AS character_data) AS external_language,
CAST('GENERAL' AS character_data) AS parameter_style,
CAST(CASE WHEN p.provolatile = 'i' THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_deterministic,
CAST('MODIFIES' AS character_data) AS sql_data_access,
CAST(CASE WHEN p.prokind <> 'p' THEN
CASE WHEN p.proisstrict THEN 'YES' ELSE 'NO' END END AS yes_or_no) AS is_null_call,
CAST(null AS character_data) AS sql_path,
CAST('YES' AS yes_or_no) AS schema_level_routine,
CAST(0 AS cardinal_number) AS max_dynamic_result_sets,
CAST(null AS yes_or_no) AS is_user_defined_cast,
CAST(null AS yes_or_no) AS is_implicitly_invocable,
CAST(CASE WHEN p.prosecdef THEN 'DEFINER' ELSE 'INVOKER' END AS character_data) AS security_type,
CAST(null AS sql_identifier) AS to_sql_specific_catalog,
CAST(null AS sql_identifier) AS to_sql_specific_schema,
CAST(null AS sql_identifier) AS to_sql_specific_name,
CAST('NO' AS yes_or_no) AS as_locator,
CAST(null AS time_stamp) AS created,
CAST(null AS time_stamp) AS last_altered,
CAST(null AS yes_or_no) AS new_savepoint_level,
CAST('NO' AS yes_or_no) AS is_udt_dependent,
CAST(null AS character_data) AS result_cast_from_data_type,
CAST(null AS yes_or_no) AS result_cast_as_locator,
CAST(null AS cardinal_number) AS result_cast_char_max_length,
CAST(null AS cardinal_number) AS result_cast_char_octet_length,
CAST(null AS sql_identifier) AS result_cast_char_set_catalog,
CAST(null AS sql_identifier) AS result_cast_char_set_schema,
CAST(null AS sql_identifier) AS result_cast_char_set_name,
CAST(null AS sql_identifier) AS result_cast_collation_catalog,
CAST(null AS sql_identifier) AS result_cast_collation_schema,
CAST(null AS sql_identifier) AS result_cast_collation_name,
CAST(null AS cardinal_number) AS result_cast_numeric_precision,
CAST(null AS cardinal_number) AS result_cast_numeric_precision_radix,
CAST(null AS cardinal_number) AS result_cast_numeric_scale,
CAST(null AS cardinal_number) AS result_cast_datetime_precision,
CAST(null AS character_data) AS result_cast_interval_type,
CAST(null AS cardinal_number) AS result_cast_interval_precision,
CAST(null AS sql_identifier) AS result_cast_type_udt_catalog,
CAST(null AS sql_identifier) AS result_cast_type_udt_schema,
CAST(null AS sql_identifier) AS result_cast_type_udt_name,
CAST(null AS sql_identifier) AS result_cast_scope_catalog,
CAST(null AS sql_identifier) AS result_cast_scope_schema,
CAST(null AS sql_identifier) AS result_cast_scope_name,
CAST(null AS cardinal_number) AS result_cast_maximum_cardinality,
CAST(null AS sql_identifier) AS result_cast_dtd_identifier
FROM (pg_namespace n
JOIN pg_proc p ON n.oid = p.pronamespace
JOIN pg_language l ON p.prolang = l.oid)
LEFT JOIN
(pg_type t JOIN pg_namespace nt ON t.typnamespace = nt.oid)
ON p.prorettype = t.oid AND p.prokind <> 'p'
WHERE (pg_has_role(p.proowner, 'USAGE')
OR has_function_privilege(p.oid, 'EXECUTE'));
GRANT SELECT ON routines TO PUBLIC;
/*
* 6.56
* SCHEMATA view
*/
CREATE VIEW schemata AS
SELECT CAST(current_database() AS sql_identifier) AS catalog_name,
CAST(n.nspname AS sql_identifier) AS schema_name,
CAST(u.rolname AS sql_identifier) AS schema_owner,
CAST(null AS sql_identifier) AS default_character_set_catalog,
CAST(null AS sql_identifier) AS default_character_set_schema,
CAST(null AS sql_identifier) AS default_character_set_name,
CAST(null AS character_data) AS sql_path
FROM pg_namespace n, pg_authid u
WHERE n.nspowner = u.oid
AND (pg_has_role(n.nspowner, 'USAGE')
OR has_schema_privilege(n.oid, 'CREATE, USAGE'));
GRANT SELECT ON schemata TO PUBLIC;
/*
* 6.57
* SEQUENCES view
*/
CREATE VIEW sequences AS
SELECT CAST(current_database() AS sql_identifier) AS sequence_catalog,
CAST(nc.nspname AS sql_identifier) AS sequence_schema,
CAST(c.relname AS sql_identifier) AS sequence_name,
CAST(format_type(s.seqtypid, null) AS character_data) AS data_type,
CAST(_pg_numeric_precision(s.seqtypid, -1) AS cardinal_number) AS numeric_precision,
CAST(2 AS cardinal_number) AS numeric_precision_radix,
CAST(0 AS cardinal_number) AS numeric_scale,
CAST(s.seqstart AS character_data) AS start_value,
CAST(s.seqmin AS character_data) AS minimum_value,
CAST(s.seqmax AS character_data) AS maximum_value,
CAST(s.seqincrement AS character_data) AS increment,
CAST(CASE WHEN s.seqcycle THEN 'YES' ELSE 'NO' END AS yes_or_no) AS cycle_option
FROM pg_namespace nc, pg_class c, pg_sequence s
WHERE c.relnamespace = nc.oid
AND c.relkind = 'S'
AND NOT EXISTS (SELECT 1 FROM pg_depend WHERE classid = 'pg_class'::regclass AND objid = c.oid AND deptype = 'i')
AND (NOT pg_is_other_temp_schema(nc.oid))
AND c.oid = s.seqrelid
AND (pg_has_role(c.relowner, 'USAGE')
OR has_sequence_privilege(c.oid, 'SELECT, UPDATE, USAGE') );
GRANT SELECT ON sequences TO PUBLIC;
/*
* 6.58
* SQL_FEATURES table
*/
CREATE TABLE sql_features (
feature_id character_data,
feature_name character_data,
sub_feature_id character_data,
sub_feature_name character_data,
is_supported yes_or_no,
is_verified_by character_data,
comments character_data
);
-- Will be filled with external data by initdb.
GRANT SELECT ON sql_features TO PUBLIC;
/*
* 6.59
* SQL_IMPLEMENTATION_INFO table
*/
CREATE TABLE sql_implementation_info (
implementation_info_id character_data,
implementation_info_name character_data,
integer_value cardinal_number,
character_value character_data,
comments character_data
);
INSERT INTO sql_implementation_info VALUES ('10003', 'CATALOG NAME', NULL, 'Y', NULL);
INSERT INTO sql_implementation_info VALUES ('10004', 'COLLATING SEQUENCE', NULL, (SELECT default_collate_name FROM character_sets), NULL);
INSERT INTO sql_implementation_info VALUES ('23', 'CURSOR COMMIT BEHAVIOR', 1, NULL, 'close cursors and retain prepared statements');
INSERT INTO sql_implementation_info VALUES ('2', 'DATA SOURCE NAME', NULL, '', NULL);
INSERT INTO sql_implementation_info VALUES ('17', 'DBMS NAME', NULL, (select trim(trailing ' ' from substring(version() from '^[^0-9]*'))), NULL);
INSERT INTO sql_implementation_info VALUES ('18', 'DBMS VERSION', NULL, '???', NULL); -- filled by initdb
INSERT INTO sql_implementation_info VALUES ('26', 'DEFAULT TRANSACTION ISOLATION', 2, NULL, 'READ COMMITTED; user-settable');
INSERT INTO sql_implementation_info VALUES ('28', 'IDENTIFIER CASE', 3, NULL, 'stored in mixed case - case sensitive');
INSERT INTO sql_implementation_info VALUES ('85', 'NULL COLLATION', 0, NULL, 'nulls higher than non-nulls');
INSERT INTO sql_implementation_info VALUES ('13', 'SERVER NAME', NULL, '', NULL);
INSERT INTO sql_implementation_info VALUES ('94', 'SPECIAL CHARACTERS', NULL, '', 'all non-ASCII characters allowed');
INSERT INTO sql_implementation_info VALUES ('46', 'TRANSACTION CAPABLE', 2, NULL, 'both DML and DDL');
GRANT SELECT ON sql_implementation_info TO PUBLIC;
/*
* 6.60
* SQL_PARTS table
*/
CREATE TABLE sql_parts (
feature_id character_data,
feature_name character_data,
is_supported yes_or_no,
is_verified_by character_data,
comments character_data
);
INSERT INTO sql_parts VALUES ('1', 'Framework (SQL/Framework)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('2', 'Foundation (SQL/Foundation)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('3', 'Call-Level Interface (SQL/CLI)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('4', 'Persistent Stored Modules (SQL/PSM)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('9', 'Management of External Data (SQL/MED)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('10', 'Object Language Bindings (SQL/OLB)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('11', 'Information and Definition Schema (SQL/Schemata)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('13', 'Routines and Types Using the Java Programming Language (SQL/JRT)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('14', 'XML-Related Specifications (SQL/XML)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('15', 'Multi-Dimensional Arrays (SQL/MDA)', 'NO', NULL, '');
INSERT INTO sql_parts VALUES ('16', 'Property Graph Queries (SQL/PGQ)', 'NO', NULL, '');
/*
* 6.61
* SQL_SIZING table
*/
CREATE TABLE sql_sizing (
sizing_id cardinal_number,
sizing_name character_data,
supported_value cardinal_number,
comments character_data
);
INSERT INTO sql_sizing VALUES (34, 'MAXIMUM CATALOG NAME LENGTH', 63, NULL);
INSERT INTO sql_sizing VALUES (30, 'MAXIMUM COLUMN NAME LENGTH', 63, NULL);
INSERT INTO sql_sizing VALUES (97, 'MAXIMUM COLUMNS IN GROUP BY', 0, NULL);
INSERT INTO sql_sizing VALUES (99, 'MAXIMUM COLUMNS IN ORDER BY', 0, NULL);
INSERT INTO sql_sizing VALUES (100, 'MAXIMUM COLUMNS IN SELECT', 1664, NULL); -- match MaxTupleAttributeNumber
INSERT INTO sql_sizing VALUES (101, 'MAXIMUM COLUMNS IN TABLE', 1600, NULL); -- match MaxHeapAttributeNumber
INSERT INTO sql_sizing VALUES (1, 'MAXIMUM CONCURRENT ACTIVITIES', 0, NULL);
INSERT INTO sql_sizing VALUES (31, 'MAXIMUM CURSOR NAME LENGTH', 63, NULL);
INSERT INTO sql_sizing VALUES (0, 'MAXIMUM DRIVER CONNECTIONS', NULL, NULL);
INSERT INTO sql_sizing VALUES (10005, 'MAXIMUM IDENTIFIER LENGTH', 63, NULL);
INSERT INTO sql_sizing VALUES (32, 'MAXIMUM SCHEMA NAME LENGTH', 63, NULL);
INSERT INTO sql_sizing VALUES (20000, 'MAXIMUM STATEMENT OCTETS', 0, NULL);
INSERT INTO sql_sizing VALUES (20001, 'MAXIMUM STATEMENT OCTETS DATA', 0, NULL);
INSERT INTO sql_sizing VALUES (20002, 'MAXIMUM STATEMENT OCTETS SCHEMA', 0, NULL);
INSERT INTO sql_sizing VALUES (35, 'MAXIMUM TABLE NAME LENGTH', 63, NULL);
INSERT INTO sql_sizing VALUES (106, 'MAXIMUM TABLES IN SELECT', 0, NULL);
INSERT INTO sql_sizing VALUES (107, 'MAXIMUM USER NAME LENGTH', 63, NULL);
INSERT INTO sql_sizing VALUES (25000, 'MAXIMUM CURRENT DEFAULT TRANSFORM GROUP LENGTH', NULL, NULL);
INSERT INTO sql_sizing VALUES (25001, 'MAXIMUM CURRENT TRANSFORM GROUP LENGTH', NULL, NULL);
INSERT INTO sql_sizing VALUES (25002, 'MAXIMUM CURRENT PATH LENGTH', 0, NULL);
INSERT INTO sql_sizing VALUES (25003, 'MAXIMUM CURRENT ROLE LENGTH', NULL, NULL);
INSERT INTO sql_sizing VALUES (25004, 'MAXIMUM SESSION USER LENGTH', 63, NULL);
INSERT INTO sql_sizing VALUES (25005, 'MAXIMUM SYSTEM USER LENGTH', 63, NULL);
UPDATE sql_sizing
SET supported_value = (SELECT typlen-1 FROM pg_catalog.pg_type WHERE typname = 'name'),
comments = 'Might be less, depending on character set.'
WHERE supported_value = 63;
GRANT SELECT ON sql_sizing TO PUBLIC;
/*
* 6.62
* TABLE_CONSTRAINTS view
*/
CREATE VIEW table_constraints AS
SELECT CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(nc.nspname AS sql_identifier) AS constraint_schema,
CAST(c.conname AS sql_identifier) AS constraint_name,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nr.nspname AS sql_identifier) AS table_schema,
CAST(r.relname AS sql_identifier) AS table_name,
CAST(
CASE c.contype WHEN 'c' THEN 'CHECK'
WHEN 'f' THEN 'FOREIGN KEY'
WHEN 'p' THEN 'PRIMARY KEY'
WHEN 'u' THEN 'UNIQUE' END
AS character_data) AS constraint_type,
CAST(CASE WHEN c.condeferrable THEN 'YES' ELSE 'NO' END AS yes_or_no)
AS is_deferrable,
CAST(CASE WHEN c.condeferred THEN 'YES' ELSE 'NO' END AS yes_or_no)
AS initially_deferred,
CAST('YES' AS yes_or_no) AS enforced,
CAST(CASE WHEN c.contype = 'u'
THEN CASE WHEN (SELECT NOT indnullsnotdistinct FROM pg_index WHERE indexrelid = conindid) THEN 'YES' ELSE 'NO' END
END
AS yes_or_no) AS nulls_distinct
FROM pg_namespace nc,
pg_namespace nr,
pg_constraint c,
pg_class r
WHERE nc.oid = c.connamespace AND nr.oid = r.relnamespace
AND c.conrelid = r.oid
AND c.contype NOT IN ('t', 'x') -- ignore nonstandard constraints
AND r.relkind IN ('r', 'p')
AND (NOT pg_is_other_temp_schema(nr.oid))
AND (pg_has_role(r.relowner, 'USAGE')
-- SELECT privilege omitted, per SQL standard
OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER')
OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES') )
UNION ALL
-- not-null constraints
SELECT CAST(current_database() AS sql_identifier) AS constraint_catalog,
CAST(nr.nspname AS sql_identifier) AS constraint_schema,
CAST(CAST(nr.oid AS text) || '_' || CAST(r.oid AS text) || '_' || CAST(a.attnum AS text) || '_not_null' AS sql_identifier) AS constraint_name, -- XXX
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nr.nspname AS sql_identifier) AS table_schema,
CAST(r.relname AS sql_identifier) AS table_name,
CAST('CHECK' AS character_data) AS constraint_type,
CAST('NO' AS yes_or_no) AS is_deferrable,
CAST('NO' AS yes_or_no) AS initially_deferred,
CAST('YES' AS yes_or_no) AS enforced,
CAST(NULL AS yes_or_no) AS nulls_distinct
FROM pg_namespace nr,
pg_class r,
pg_attribute a
WHERE nr.oid = r.relnamespace
AND r.oid = a.attrelid
AND a.attnotnull
AND a.attnum > 0
AND NOT a.attisdropped
AND r.relkind IN ('r', 'p')
AND (NOT pg_is_other_temp_schema(nr.oid))
AND (pg_has_role(r.relowner, 'USAGE')
-- SELECT privilege omitted, per SQL standard
OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER')
OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES') );
GRANT SELECT ON table_constraints TO PUBLIC;
/*
* 6.63
* TABLE_METHOD_PRIVILEGES view
*/
-- feature not supported
/*
* 6.64
* TABLE_PRIVILEGES view
*/
CREATE VIEW table_privileges AS
SELECT CAST(u_grantor.rolname AS sql_identifier) AS grantor,
CAST(grantee.rolname AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nc.nspname AS sql_identifier) AS table_schema,
CAST(c.relname AS sql_identifier) AS table_name,
CAST(c.prtype AS character_data) AS privilege_type,
CAST(
CASE WHEN
-- object owner always has grant options
pg_has_role(grantee.oid, c.relowner, 'USAGE')
OR c.grantable
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable,
CAST(CASE WHEN c.prtype = 'SELECT' THEN 'YES' ELSE 'NO' END AS yes_or_no) AS with_hierarchy
FROM (
SELECT oid, relname, relnamespace, relkind, relowner, (aclexplode(coalesce(relacl, acldefault('r', relowner)))).* FROM pg_class
) AS c (oid, relname, relnamespace, relkind, relowner, grantor, grantee, prtype, grantable),
pg_namespace nc,
pg_authid u_grantor,
(
SELECT oid, rolname FROM pg_authid
UNION ALL
SELECT 0::oid, 'PUBLIC'
) AS grantee (oid, rolname)
WHERE c.relnamespace = nc.oid
AND c.relkind IN ('r', 'v', 'f', 'p')
AND c.grantee = grantee.oid
AND c.grantor = u_grantor.oid
AND c.prtype IN ('INSERT', 'SELECT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER')
AND (pg_has_role(u_grantor.oid, 'USAGE')
OR pg_has_role(grantee.oid, 'USAGE')
OR grantee.rolname = 'PUBLIC');
GRANT SELECT ON table_privileges TO PUBLIC;
/*
* 6.45
* ROLE_TABLE_GRANTS view
*/
CREATE VIEW role_table_grants AS
SELECT grantor,
grantee,
table_catalog,
table_schema,
table_name,
privilege_type,
is_grantable,
with_hierarchy
FROM table_privileges
WHERE grantor IN (SELECT role_name FROM enabled_roles)
OR grantee IN (SELECT role_name FROM enabled_roles);
GRANT SELECT ON role_table_grants TO PUBLIC;
/*
* 6.65
* TABLES view
*/
CREATE VIEW tables AS
SELECT CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nc.nspname AS sql_identifier) AS table_schema,
CAST(c.relname AS sql_identifier) AS table_name,
CAST(
CASE WHEN nc.oid = pg_my_temp_schema() THEN 'LOCAL TEMPORARY'
WHEN c.relkind IN ('r', 'p') THEN 'BASE TABLE'
WHEN c.relkind = 'v' THEN 'VIEW'
WHEN c.relkind = 'f' THEN 'FOREIGN'
ELSE null END
AS character_data) AS table_type,
CAST(null AS sql_identifier) AS self_referencing_column_name,
CAST(null AS character_data) AS reference_generation,
CAST(CASE WHEN t.typname IS NOT NULL THEN current_database() ELSE null END AS sql_identifier) AS user_defined_type_catalog,
CAST(nt.nspname AS sql_identifier) AS user_defined_type_schema,
CAST(t.typname AS sql_identifier) AS user_defined_type_name,
CAST(CASE WHEN c.relkind IN ('r', 'p') OR
(c.relkind IN ('v', 'f') AND
-- 1 << CMD_INSERT
pg_relation_is_updatable(c.oid, false) & 8 = 8)
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_insertable_into,
CAST(CASE WHEN t.typname IS NOT NULL THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_typed,
CAST(null AS character_data) AS commit_action
FROM pg_namespace nc JOIN pg_class c ON (nc.oid = c.relnamespace)
LEFT JOIN (pg_type t JOIN pg_namespace nt ON (t.typnamespace = nt.oid)) ON (c.reloftype = t.oid)
WHERE c.relkind IN ('r', 'v', 'f', 'p')
AND (NOT pg_is_other_temp_schema(nc.oid))
AND (pg_has_role(c.relowner, 'USAGE')
OR has_table_privilege(c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER')
OR has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES') );
GRANT SELECT ON tables TO PUBLIC;
/*
* 6.66
* TRANSFORMS view
*/
CREATE VIEW transforms AS
SELECT CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(nt.nspname AS sql_identifier) AS udt_schema,
CAST(t.typname AS sql_identifier) AS udt_name,
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(np.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name,
CAST(l.lanname AS sql_identifier) AS group_name,
CAST('FROM SQL' AS character_data) AS transform_type
FROM pg_type t JOIN pg_transform x ON t.oid = x.trftype
JOIN pg_language l ON x.trflang = l.oid
JOIN pg_proc p ON x.trffromsql = p.oid
JOIN pg_namespace nt ON t.typnamespace = nt.oid
JOIN pg_namespace np ON p.pronamespace = np.oid
UNION
SELECT CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(nt.nspname AS sql_identifier) AS udt_schema,
CAST(t.typname AS sql_identifier) AS udt_name,
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(np.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name,
CAST(l.lanname AS sql_identifier) AS group_name,
CAST('TO SQL' AS character_data) AS transform_type
FROM pg_type t JOIN pg_transform x ON t.oid = x.trftype
JOIN pg_language l ON x.trflang = l.oid
JOIN pg_proc p ON x.trftosql = p.oid
JOIN pg_namespace nt ON t.typnamespace = nt.oid
JOIN pg_namespace np ON p.pronamespace = np.oid
ORDER BY udt_catalog, udt_schema, udt_name, group_name, transform_type -- some sensible grouping for interactive use
;
/*
* 6.67
* TRANSLATIONS view
*/
-- feature not supported
/*
* 6.68
* TRIGGERED_UPDATE_COLUMNS view
*/
CREATE VIEW triggered_update_columns AS
SELECT CAST(current_database() AS sql_identifier) AS trigger_catalog,
CAST(n.nspname AS sql_identifier) AS trigger_schema,
CAST(t.tgname AS sql_identifier) AS trigger_name,
CAST(current_database() AS sql_identifier) AS event_object_catalog,
CAST(n.nspname AS sql_identifier) AS event_object_schema,
CAST(c.relname AS sql_identifier) AS event_object_table,
CAST(a.attname AS sql_identifier) AS event_object_column
FROM pg_namespace n, pg_class c, pg_trigger t,
(SELECT tgoid, (ta0.tgat).x AS tgattnum, (ta0.tgat).n AS tgattpos
FROM (SELECT oid AS tgoid, information_schema._pg_expandarray(tgattr) AS tgat FROM pg_trigger) AS ta0) AS ta,
pg_attribute a
WHERE n.oid = c.relnamespace
AND c.oid = t.tgrelid
AND t.oid = ta.tgoid
AND (a.attrelid, a.attnum) = (t.tgrelid, ta.tgattnum)
AND NOT t.tgisinternal
AND (NOT pg_is_other_temp_schema(n.oid))
AND (pg_has_role(c.relowner, 'USAGE')
-- SELECT privilege omitted, per SQL standard
OR has_column_privilege(c.oid, a.attnum, 'INSERT, UPDATE, REFERENCES') );
GRANT SELECT ON triggered_update_columns TO PUBLIC;
/*
* 6.69
* TRIGGER_COLUMN_USAGE view
*/
-- not tracked by PostgreSQL
/*
* 6.70
* TRIGGER_PERIOD_USAGE view
*/
-- feature not supported
/*
* 6.71
* TRIGGER_ROUTINE_USAGE view
*/
-- not tracked by PostgreSQL
/*
* 6.72
* TRIGGER_SEQUENCE_USAGE view
*/
-- not tracked by PostgreSQL
/*
* 6.73
* TRIGGER_TABLE_USAGE view
*/
-- not tracked by PostgreSQL
/*
* 6.74
* TRIGGERS view
*/
CREATE VIEW triggers AS
SELECT CAST(current_database() AS sql_identifier) AS trigger_catalog,
CAST(n.nspname AS sql_identifier) AS trigger_schema,
CAST(t.tgname AS sql_identifier) AS trigger_name,
CAST(em.text AS character_data) AS event_manipulation,
CAST(current_database() AS sql_identifier) AS event_object_catalog,
CAST(n.nspname AS sql_identifier) AS event_object_schema,
CAST(c.relname AS sql_identifier) AS event_object_table,
CAST(
-- To determine action order, partition by schema, table,
-- event_manipulation (INSERT/DELETE/UPDATE), ROW/STATEMENT (1),
-- BEFORE/AFTER (66), then order by trigger name. It's preferable
-- to partition by view output columns, so that query constraints
-- can be pushed down below the window function.
rank() OVER (PARTITION BY CAST(n.nspname AS sql_identifier),
CAST(c.relname AS sql_identifier),
em.num,
t.tgtype & 1,
t.tgtype & 66
ORDER BY t.tgname)
AS cardinal_number) AS action_order,
CAST(
CASE WHEN pg_has_role(c.relowner, 'USAGE')
THEN (regexp_match(pg_get_triggerdef(t.oid), E'.{35,} WHEN \\((.+)\\) EXECUTE FUNCTION'))[1]
ELSE null END
AS character_data) AS action_condition,
CAST(
substring(pg_get_triggerdef(t.oid) from
position('EXECUTE FUNCTION' in substring(pg_get_triggerdef(t.oid) from 48)) + 47)
AS character_data) AS action_statement,
CAST(
-- hard-wired reference to TRIGGER_TYPE_ROW
CASE t.tgtype & 1 WHEN 1 THEN 'ROW' ELSE 'STATEMENT' END
AS character_data) AS action_orientation,
CAST(
-- hard-wired refs to TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSTEAD
CASE t.tgtype & 66 WHEN 2 THEN 'BEFORE' WHEN 64 THEN 'INSTEAD OF' ELSE 'AFTER' END
AS character_data) AS action_timing,
CAST(tgoldtable AS sql_identifier) AS action_reference_old_table,
CAST(tgnewtable AS sql_identifier) AS action_reference_new_table,
CAST(null AS sql_identifier) AS action_reference_old_row,
CAST(null AS sql_identifier) AS action_reference_new_row,
CAST(null AS time_stamp) AS created
FROM pg_namespace n, pg_class c, pg_trigger t,
-- hard-wired refs to TRIGGER_TYPE_INSERT, TRIGGER_TYPE_DELETE,
-- TRIGGER_TYPE_UPDATE; we intentionally omit TRIGGER_TYPE_TRUNCATE
(VALUES (4, 'INSERT'),
(8, 'DELETE'),
(16, 'UPDATE')) AS em (num, text)
WHERE n.oid = c.relnamespace
AND c.oid = t.tgrelid
AND t.tgtype & em.num <> 0
AND NOT t.tgisinternal
AND (NOT pg_is_other_temp_schema(n.oid))
AND (pg_has_role(c.relowner, 'USAGE')
-- SELECT privilege omitted, per SQL standard
OR has_table_privilege(c.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER')
OR has_any_column_privilege(c.oid, 'INSERT, UPDATE, REFERENCES') );
GRANT SELECT ON triggers TO PUBLIC;
/*
* 6.75
* UDT_PRIVILEGES view
*/
CREATE VIEW udt_privileges AS
SELECT CAST(u_grantor.rolname AS sql_identifier) AS grantor,
CAST(grantee.rolname AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(n.nspname AS sql_identifier) AS udt_schema,
CAST(t.typname AS sql_identifier) AS udt_name,
CAST('TYPE USAGE' AS character_data) AS privilege_type, -- sic
CAST(
CASE WHEN
-- object owner always has grant options
pg_has_role(grantee.oid, t.typowner, 'USAGE')
OR t.grantable
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable
FROM (
SELECT oid, typname, typnamespace, typtype, typowner, (aclexplode(coalesce(typacl, acldefault('T', typowner)))).* FROM pg_type
) AS t (oid, typname, typnamespace, typtype, typowner, grantor, grantee, prtype, grantable),
pg_namespace n,
pg_authid u_grantor,
(
SELECT oid, rolname FROM pg_authid
UNION ALL
SELECT 0::oid, 'PUBLIC'
) AS grantee (oid, rolname)
WHERE t.typnamespace = n.oid
AND t.typtype = 'c'
AND t.grantee = grantee.oid
AND t.grantor = u_grantor.oid
AND t.prtype IN ('USAGE')
AND (pg_has_role(u_grantor.oid, 'USAGE')
OR pg_has_role(grantee.oid, 'USAGE')
OR grantee.rolname = 'PUBLIC');
GRANT SELECT ON udt_privileges TO PUBLIC;
/*
* 6.48
* ROLE_UDT_GRANTS view
*/
CREATE VIEW role_udt_grants AS
SELECT grantor,
grantee,
udt_catalog,
udt_schema,
udt_name,
privilege_type,
is_grantable
FROM udt_privileges
WHERE grantor IN (SELECT role_name FROM enabled_roles)
OR grantee IN (SELECT role_name FROM enabled_roles);
GRANT SELECT ON role_udt_grants TO PUBLIC;
/*
* 6.76
* USAGE_PRIVILEGES view
*/
CREATE VIEW usage_privileges AS
/* collations */
-- Collations have no real privileges, so we represent all collations with implicit usage privilege here.
SELECT CAST(u.rolname AS sql_identifier) AS grantor,
CAST('PUBLIC' AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS object_catalog,
CAST(n.nspname AS sql_identifier) AS object_schema,
CAST(c.collname AS sql_identifier) AS object_name,
CAST('COLLATION' AS character_data) AS object_type,
CAST('USAGE' AS character_data) AS privilege_type,
CAST('NO' AS yes_or_no) AS is_grantable
FROM pg_authid u,
pg_namespace n,
pg_collation c
WHERE u.oid = c.collowner
AND c.collnamespace = n.oid
AND collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database()))
UNION ALL
/* domains */
SELECT CAST(u_grantor.rolname AS sql_identifier) AS grantor,
CAST(grantee.rolname AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS object_catalog,
CAST(n.nspname AS sql_identifier) AS object_schema,
CAST(t.typname AS sql_identifier) AS object_name,
CAST('DOMAIN' AS character_data) AS object_type,
CAST('USAGE' AS character_data) AS privilege_type,
CAST(
CASE WHEN
-- object owner always has grant options
pg_has_role(grantee.oid, t.typowner, 'USAGE')
OR t.grantable
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable
FROM (
SELECT oid, typname, typnamespace, typtype, typowner, (aclexplode(coalesce(typacl, acldefault('T', typowner)))).* FROM pg_type
) AS t (oid, typname, typnamespace, typtype, typowner, grantor, grantee, prtype, grantable),
pg_namespace n,
pg_authid u_grantor,
(
SELECT oid, rolname FROM pg_authid
UNION ALL
SELECT 0::oid, 'PUBLIC'
) AS grantee (oid, rolname)
WHERE t.typnamespace = n.oid
AND t.typtype = 'd'
AND t.grantee = grantee.oid
AND t.grantor = u_grantor.oid
AND t.prtype IN ('USAGE')
AND (pg_has_role(u_grantor.oid, 'USAGE')
OR pg_has_role(grantee.oid, 'USAGE')
OR grantee.rolname = 'PUBLIC')
UNION ALL
/* foreign-data wrappers */
SELECT CAST(u_grantor.rolname AS sql_identifier) AS grantor,
CAST(grantee.rolname AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS object_catalog,
CAST('' AS sql_identifier) AS object_schema,
CAST(fdw.fdwname AS sql_identifier) AS object_name,
CAST('FOREIGN DATA WRAPPER' AS character_data) AS object_type,
CAST('USAGE' AS character_data) AS privilege_type,
CAST(
CASE WHEN
-- object owner always has grant options
pg_has_role(grantee.oid, fdw.fdwowner, 'USAGE')
OR fdw.grantable
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable
FROM (
SELECT fdwname, fdwowner, (aclexplode(coalesce(fdwacl, acldefault('F', fdwowner)))).* FROM pg_foreign_data_wrapper
) AS fdw (fdwname, fdwowner, grantor, grantee, prtype, grantable),
pg_authid u_grantor,
(
SELECT oid, rolname FROM pg_authid
UNION ALL
SELECT 0::oid, 'PUBLIC'
) AS grantee (oid, rolname)
WHERE u_grantor.oid = fdw.grantor
AND grantee.oid = fdw.grantee
AND fdw.prtype IN ('USAGE')
AND (pg_has_role(u_grantor.oid, 'USAGE')
OR pg_has_role(grantee.oid, 'USAGE')
OR grantee.rolname = 'PUBLIC')
UNION ALL
/* foreign servers */
SELECT CAST(u_grantor.rolname AS sql_identifier) AS grantor,
CAST(grantee.rolname AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS object_catalog,
CAST('' AS sql_identifier) AS object_schema,
CAST(srv.srvname AS sql_identifier) AS object_name,
CAST('FOREIGN SERVER' AS character_data) AS object_type,
CAST('USAGE' AS character_data) AS privilege_type,
CAST(
CASE WHEN
-- object owner always has grant options
pg_has_role(grantee.oid, srv.srvowner, 'USAGE')
OR srv.grantable
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable
FROM (
SELECT srvname, srvowner, (aclexplode(coalesce(srvacl, acldefault('S', srvowner)))).* FROM pg_foreign_server
) AS srv (srvname, srvowner, grantor, grantee, prtype, grantable),
pg_authid u_grantor,
(
SELECT oid, rolname FROM pg_authid
UNION ALL
SELECT 0::oid, 'PUBLIC'
) AS grantee (oid, rolname)
WHERE u_grantor.oid = srv.grantor
AND grantee.oid = srv.grantee
AND srv.prtype IN ('USAGE')
AND (pg_has_role(u_grantor.oid, 'USAGE')
OR pg_has_role(grantee.oid, 'USAGE')
OR grantee.rolname = 'PUBLIC')
UNION ALL
/* sequences */
SELECT CAST(u_grantor.rolname AS sql_identifier) AS grantor,
CAST(grantee.rolname AS sql_identifier) AS grantee,
CAST(current_database() AS sql_identifier) AS object_catalog,
CAST(n.nspname AS sql_identifier) AS object_schema,
CAST(c.relname AS sql_identifier) AS object_name,
CAST('SEQUENCE' AS character_data) AS object_type,
CAST('USAGE' AS character_data) AS privilege_type,
CAST(
CASE WHEN
-- object owner always has grant options
pg_has_role(grantee.oid, c.relowner, 'USAGE')
OR c.grantable
THEN 'YES' ELSE 'NO' END AS yes_or_no) AS is_grantable
FROM (
SELECT oid, relname, relnamespace, relkind, relowner, (aclexplode(coalesce(relacl, acldefault('r', relowner)))).* FROM pg_class
) AS c (oid, relname, relnamespace, relkind, relowner, grantor, grantee, prtype, grantable),
pg_namespace n,
pg_authid u_grantor,
(
SELECT oid, rolname FROM pg_authid
UNION ALL
SELECT 0::oid, 'PUBLIC'
) AS grantee (oid, rolname)
WHERE c.relnamespace = n.oid
AND c.relkind = 'S'
AND c.grantee = grantee.oid
AND c.grantor = u_grantor.oid
AND c.prtype IN ('USAGE')
AND (pg_has_role(u_grantor.oid, 'USAGE')
OR pg_has_role(grantee.oid, 'USAGE')
OR grantee.rolname = 'PUBLIC');
GRANT SELECT ON usage_privileges TO PUBLIC;
/*
* 6.47
* ROLE_USAGE_GRANTS view
*/
CREATE VIEW role_usage_grants AS
SELECT grantor,
grantee,
object_catalog,
object_schema,
object_name,
object_type,
privilege_type,
is_grantable
FROM usage_privileges
WHERE grantor IN (SELECT role_name FROM enabled_roles)
OR grantee IN (SELECT role_name FROM enabled_roles);
GRANT SELECT ON role_usage_grants TO PUBLIC;
/*
* 6.77
* USER_DEFINED_TYPES view
*/
CREATE VIEW user_defined_types AS
SELECT CAST(current_database() AS sql_identifier) AS user_defined_type_catalog,
CAST(n.nspname AS sql_identifier) AS user_defined_type_schema,
CAST(c.relname AS sql_identifier) AS user_defined_type_name,
CAST('STRUCTURED' AS character_data) AS user_defined_type_category,
CAST('YES' AS yes_or_no) AS is_instantiable,
CAST(null AS yes_or_no) AS is_final,
CAST(null AS character_data) AS ordering_form,
CAST(null AS character_data) AS ordering_category,
CAST(null AS sql_identifier) AS ordering_routine_catalog,
CAST(null AS sql_identifier) AS ordering_routine_schema,
CAST(null AS sql_identifier) AS ordering_routine_name,
CAST(null AS character_data) AS reference_type,
CAST(null AS character_data) AS data_type,
CAST(null AS cardinal_number) AS character_maximum_length,
CAST(null AS cardinal_number) AS character_octet_length,
CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(null AS sql_identifier) AS character_set_name,
CAST(null AS sql_identifier) AS collation_catalog,
CAST(null AS sql_identifier) AS collation_schema,
CAST(null AS sql_identifier) AS collation_name,
CAST(null AS cardinal_number) AS numeric_precision,
CAST(null AS cardinal_number) AS numeric_precision_radix,
CAST(null AS cardinal_number) AS numeric_scale,
CAST(null AS cardinal_number) AS datetime_precision,
CAST(null AS character_data) AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
CAST(null AS sql_identifier) AS source_dtd_identifier,
CAST(null AS sql_identifier) AS ref_dtd_identifier
FROM pg_namespace n, pg_class c, pg_type t
WHERE n.oid = c.relnamespace
AND t.typrelid = c.oid
AND c.relkind = 'c'
AND (pg_has_role(t.typowner, 'USAGE')
OR has_type_privilege(t.oid, 'USAGE'));
GRANT SELECT ON user_defined_types TO PUBLIC;
/*
* 6.78
* VIEW_COLUMN_USAGE
*/
CREATE VIEW view_column_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS view_catalog,
CAST(nv.nspname AS sql_identifier) AS view_schema,
CAST(v.relname AS sql_identifier) AS view_name,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nt.nspname AS sql_identifier) AS table_schema,
CAST(t.relname AS sql_identifier) AS table_name,
CAST(a.attname AS sql_identifier) AS column_name
FROM pg_namespace nv, pg_class v, pg_depend dv,
pg_depend dt, pg_class t, pg_namespace nt,
pg_attribute a
WHERE nv.oid = v.relnamespace
AND v.relkind = 'v'
AND v.oid = dv.refobjid
AND dv.refclassid = 'pg_catalog.pg_class'::regclass
AND dv.classid = 'pg_catalog.pg_rewrite'::regclass
AND dv.deptype = 'i'
AND dv.objid = dt.objid
AND dv.refobjid <> dt.refobjid
AND dt.classid = 'pg_catalog.pg_rewrite'::regclass
AND dt.refclassid = 'pg_catalog.pg_class'::regclass
AND dt.refobjid = t.oid
AND t.relnamespace = nt.oid
AND t.relkind IN ('r', 'v', 'f', 'p')
AND t.oid = a.attrelid
AND dt.refobjsubid = a.attnum
AND pg_has_role(t.relowner, 'USAGE');
GRANT SELECT ON view_column_usage TO PUBLIC;
/*
* 6.79
* VIEW_PERIOD_USAGE
*/
-- feature not supported
/*
* 6.80
* VIEW_ROUTINE_USAGE
*/
CREATE VIEW view_routine_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nv.nspname AS sql_identifier) AS table_schema,
CAST(v.relname AS sql_identifier) AS table_name,
CAST(current_database() AS sql_identifier) AS specific_catalog,
CAST(np.nspname AS sql_identifier) AS specific_schema,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier) AS specific_name
FROM pg_namespace nv, pg_class v, pg_depend dv,
pg_depend dp, pg_proc p, pg_namespace np
WHERE nv.oid = v.relnamespace
AND v.relkind = 'v'
AND v.oid = dv.refobjid
AND dv.refclassid = 'pg_catalog.pg_class'::regclass
AND dv.classid = 'pg_catalog.pg_rewrite'::regclass
AND dv.deptype = 'i'
AND dv.objid = dp.objid
AND dp.classid = 'pg_catalog.pg_rewrite'::regclass
AND dp.refclassid = 'pg_catalog.pg_proc'::regclass
AND dp.refobjid = p.oid
AND p.pronamespace = np.oid
AND pg_has_role(p.proowner, 'USAGE');
GRANT SELECT ON view_routine_usage TO PUBLIC;
/*
* 6.81
* VIEW_TABLE_USAGE
*/
CREATE VIEW view_table_usage AS
SELECT DISTINCT
CAST(current_database() AS sql_identifier) AS view_catalog,
CAST(nv.nspname AS sql_identifier) AS view_schema,
CAST(v.relname AS sql_identifier) AS view_name,
CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nt.nspname AS sql_identifier) AS table_schema,
CAST(t.relname AS sql_identifier) AS table_name
FROM pg_namespace nv, pg_class v, pg_depend dv,
pg_depend dt, pg_class t, pg_namespace nt
WHERE nv.oid = v.relnamespace
AND v.relkind = 'v'
AND v.oid = dv.refobjid
AND dv.refclassid = 'pg_catalog.pg_class'::regclass
AND dv.classid = 'pg_catalog.pg_rewrite'::regclass
AND dv.deptype = 'i'
AND dv.objid = dt.objid
AND dv.refobjid <> dt.refobjid
AND dt.classid = 'pg_catalog.pg_rewrite'::regclass
AND dt.refclassid = 'pg_catalog.pg_class'::regclass
AND dt.refobjid = t.oid
AND t.relnamespace = nt.oid
AND t.relkind IN ('r', 'v', 'f', 'p')
AND pg_has_role(t.relowner, 'USAGE');
GRANT SELECT ON view_table_usage TO PUBLIC;
/*
* 6.82
* VIEWS view
*/
CREATE VIEW views AS
SELECT CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(nc.nspname AS sql_identifier) AS table_schema,
CAST(c.relname AS sql_identifier) AS table_name,
CAST(
CASE WHEN pg_has_role(c.relowner, 'USAGE')
THEN pg_get_viewdef(c.oid)
ELSE null END
AS character_data) AS view_definition,
CAST(
CASE WHEN 'check_option=cascaded' = ANY (c.reloptions)
THEN 'CASCADED'
WHEN 'check_option=local' = ANY (c.reloptions)
THEN 'LOCAL'
ELSE 'NONE' END
AS character_data) AS check_option,
CAST(
-- (1 << CMD_UPDATE) + (1 << CMD_DELETE)
CASE WHEN pg_relation_is_updatable(c.oid, false) & 20 = 20
THEN 'YES' ELSE 'NO' END
AS yes_or_no) AS is_updatable,
CAST(
-- 1 << CMD_INSERT
CASE WHEN pg_relation_is_updatable(c.oid, false) & 8 = 8
THEN 'YES' ELSE 'NO' END
AS yes_or_no) AS is_insertable_into,
CAST(
-- TRIGGER_TYPE_ROW + TRIGGER_TYPE_INSTEAD + TRIGGER_TYPE_UPDATE
CASE WHEN EXISTS (SELECT 1 FROM pg_trigger WHERE tgrelid = c.oid AND tgtype & 81 = 81)
THEN 'YES' ELSE 'NO' END
AS yes_or_no) AS is_trigger_updatable,
CAST(
-- TRIGGER_TYPE_ROW + TRIGGER_TYPE_INSTEAD + TRIGGER_TYPE_DELETE
CASE WHEN EXISTS (SELECT 1 FROM pg_trigger WHERE tgrelid = c.oid AND tgtype & 73 = 73)
THEN 'YES' ELSE 'NO' END
AS yes_or_no) AS is_trigger_deletable,
CAST(
-- TRIGGER_TYPE_ROW + TRIGGER_TYPE_INSTEAD + TRIGGER_TYPE_INSERT
CASE WHEN EXISTS (SELECT 1 FROM pg_trigger WHERE tgrelid = c.oid AND tgtype & 69 = 69)
THEN 'YES' ELSE 'NO' END
AS yes_or_no) AS is_trigger_insertable_into
FROM pg_namespace nc, pg_class c
WHERE c.relnamespace = nc.oid
AND c.relkind = 'v'
AND (NOT pg_is_other_temp_schema(nc.oid))
AND (pg_has_role(c.relowner, 'USAGE')
OR has_table_privilege(c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER')
OR has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES') );
GRANT SELECT ON views TO PUBLIC;
-- The following views have dependencies that force them to appear out of order.
/*
* 6.26
* DATA_TYPE_PRIVILEGES view
*/
CREATE VIEW data_type_privileges AS
SELECT CAST(current_database() AS sql_identifier) AS object_catalog,
CAST(x.objschema AS sql_identifier) AS object_schema,
CAST(x.objname AS sql_identifier) AS object_name,
CAST(x.objtype AS character_data) AS object_type,
CAST(x.objdtdid AS sql_identifier) AS dtd_identifier
FROM
(
SELECT udt_schema, udt_name, 'USER-DEFINED TYPE'::text, dtd_identifier FROM attributes
UNION ALL
SELECT table_schema, table_name, 'TABLE'::text, dtd_identifier FROM columns
UNION ALL
SELECT domain_schema, domain_name, 'DOMAIN'::text, dtd_identifier FROM domains
UNION ALL
SELECT specific_schema, specific_name, 'ROUTINE'::text, dtd_identifier FROM parameters
UNION ALL
SELECT specific_schema, specific_name, 'ROUTINE'::text, dtd_identifier FROM routines
) AS x (objschema, objname, objtype, objdtdid);
GRANT SELECT ON data_type_privileges TO PUBLIC;
/*
* 6.31
* ELEMENT_TYPES view
*/
CREATE VIEW element_types AS
SELECT CAST(current_database() AS sql_identifier) AS object_catalog,
CAST(n.nspname AS sql_identifier) AS object_schema,
CAST(x.objname AS sql_identifier) AS object_name,
CAST(x.objtype AS character_data) AS object_type,
CAST(x.objdtdid AS sql_identifier) AS collection_type_identifier,
CAST(
CASE WHEN nbt.nspname = 'pg_catalog' THEN format_type(bt.oid, null)
ELSE 'USER-DEFINED' END AS character_data) AS data_type,
CAST(null AS cardinal_number) AS character_maximum_length,
CAST(null AS cardinal_number) AS character_octet_length,
CAST(null AS sql_identifier) AS character_set_catalog,
CAST(null AS sql_identifier) AS character_set_schema,
CAST(null AS sql_identifier) AS character_set_name,
CAST(CASE WHEN nco.nspname IS NOT NULL THEN current_database() END AS sql_identifier) AS collation_catalog,
CAST(nco.nspname AS sql_identifier) AS collation_schema,
CAST(co.collname AS sql_identifier) AS collation_name,
CAST(null AS cardinal_number) AS numeric_precision,
CAST(null AS cardinal_number) AS numeric_precision_radix,
CAST(null AS cardinal_number) AS numeric_scale,
CAST(null AS cardinal_number) AS datetime_precision,
CAST(null AS character_data) AS interval_type,
CAST(null AS cardinal_number) AS interval_precision,
CAST(current_database() AS sql_identifier) AS udt_catalog,
CAST(nbt.nspname AS sql_identifier) AS udt_schema,
CAST(bt.typname AS sql_identifier) AS udt_name,
CAST(null AS sql_identifier) AS scope_catalog,
CAST(null AS sql_identifier) AS scope_schema,
CAST(null AS sql_identifier) AS scope_name,
CAST(null AS cardinal_number) AS maximum_cardinality,
CAST('a' || CAST(x.objdtdid AS text) AS sql_identifier) AS dtd_identifier
FROM pg_namespace n, pg_type at, pg_namespace nbt, pg_type bt,
(
/* columns, attributes */
SELECT c.relnamespace, CAST(c.relname AS sql_identifier),
CASE WHEN c.relkind = 'c' THEN 'USER-DEFINED TYPE'::text ELSE 'TABLE'::text END,
a.attnum, a.atttypid, a.attcollation
FROM pg_class c, pg_attribute a
WHERE c.oid = a.attrelid
AND c.relkind IN ('r', 'v', 'f', 'c', 'p')
AND attnum > 0 AND NOT attisdropped
UNION ALL
/* domains */
SELECT t.typnamespace, CAST(t.typname AS sql_identifier),
'DOMAIN'::text, 1, t.typbasetype, t.typcollation
FROM pg_type t
WHERE t.typtype = 'd'
UNION ALL
/* parameters */
SELECT pronamespace,
CAST(nameconcatoid(proname, oid) AS sql_identifier),
'ROUTINE'::text, (ss.x).n, (ss.x).x, 0
FROM (SELECT p.pronamespace, p.proname, p.oid,
_pg_expandarray(coalesce(p.proallargtypes, p.proargtypes::oid[])) AS x
FROM pg_proc p) AS ss
UNION ALL
/* result types */
SELECT p.pronamespace,
CAST(nameconcatoid(p.proname, p.oid) AS sql_identifier),
'ROUTINE'::text, 0, p.prorettype, 0
FROM pg_proc p
) AS x (objschema, objname, objtype, objdtdid, objtypeid, objcollation)
LEFT JOIN (pg_collation co JOIN pg_namespace nco ON (co.collnamespace = nco.oid))
ON x.objcollation = co.oid AND (nco.nspname, co.collname) <> ('pg_catalog', 'default')
WHERE n.oid = x.objschema
AND at.oid = x.objtypeid
AND (at.typelem <> 0 AND at.typlen = -1)
AND at.typelem = bt.oid
AND nbt.oid = bt.typnamespace
AND (n.nspname, x.objname, x.objtype, CAST(x.objdtdid AS sql_identifier)) IN
( SELECT object_schema, object_name, object_type, dtd_identifier
FROM data_type_privileges );
GRANT SELECT ON element_types TO PUBLIC;
-- SQL/MED views; these use section numbers from part 9 of the standard.
/* Base view for foreign table columns */
CREATE VIEW _pg_foreign_table_columns AS
SELECT n.nspname,
c.relname,
a.attname,
a.attfdwoptions
FROM pg_foreign_table t, pg_authid u, pg_namespace n, pg_class c,
pg_attribute a
WHERE u.oid = c.relowner
AND (pg_has_role(c.relowner, 'USAGE')
OR has_column_privilege(c.oid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'))
AND n.oid = c.relnamespace
AND c.oid = t.ftrelid
AND c.relkind = 'f'
AND a.attrelid = c.oid
AND a.attnum > 0;
/*
* 24.3
* COLUMN_OPTIONS view
*/
CREATE VIEW column_options AS
SELECT CAST(current_database() AS sql_identifier) AS table_catalog,
CAST(c.nspname AS sql_identifier) AS table_schema,
CAST(c.relname AS sql_identifier) AS table_name,
CAST(c.attname AS sql_identifier) AS column_name,
CAST((pg_options_to_table(c.attfdwoptions)).option_name AS sql_identifier) AS option_name,
CAST((pg_options_to_table(c.attfdwoptions)).option_value AS character_data) AS option_value
FROM _pg_foreign_table_columns c;
GRANT SELECT ON column_options TO PUBLIC;
/* Base view for foreign-data wrappers */
CREATE VIEW _pg_foreign_data_wrappers AS
SELECT w.oid,
w.fdwowner,
w.fdwoptions,
CAST(current_database() AS sql_identifier) AS foreign_data_wrapper_catalog,
CAST(fdwname AS sql_identifier) AS foreign_data_wrapper_name,
CAST(u.rolname AS sql_identifier) AS authorization_identifier,
CAST('c' AS character_data) AS foreign_data_wrapper_language
FROM pg_foreign_data_wrapper w, pg_authid u
WHERE u.oid = w.fdwowner
AND (pg_has_role(fdwowner, 'USAGE')
OR has_foreign_data_wrapper_privilege(w.oid, 'USAGE'));
/*
* 24.5
* FOREIGN_DATA_WRAPPER_OPTIONS view
*/
CREATE VIEW foreign_data_wrapper_options AS
SELECT foreign_data_wrapper_catalog,
foreign_data_wrapper_name,
CAST((pg_options_to_table(w.fdwoptions)).option_name AS sql_identifier) AS option_name,
CAST((pg_options_to_table(w.fdwoptions)).option_value AS character_data) AS option_value
FROM _pg_foreign_data_wrappers w;
GRANT SELECT ON foreign_data_wrapper_options TO PUBLIC;
/*
* 24.6
* FOREIGN_DATA_WRAPPERS view
*/
CREATE VIEW foreign_data_wrappers AS
SELECT foreign_data_wrapper_catalog,
foreign_data_wrapper_name,
authorization_identifier,
CAST(NULL AS character_data) AS library_name,
foreign_data_wrapper_language
FROM _pg_foreign_data_wrappers w;
GRANT SELECT ON foreign_data_wrappers TO PUBLIC;
/* Base view for foreign servers */
CREATE VIEW _pg_foreign_servers AS
SELECT s.oid,
s.srvoptions,
CAST(current_database() AS sql_identifier) AS foreign_server_catalog,
CAST(srvname AS sql_identifier) AS foreign_server_name,
CAST(current_database() AS sql_identifier) AS foreign_data_wrapper_catalog,
CAST(w.fdwname AS sql_identifier) AS foreign_data_wrapper_name,
CAST(srvtype AS character_data) AS foreign_server_type,
CAST(srvversion AS character_data) AS foreign_server_version,
CAST(u.rolname AS sql_identifier) AS authorization_identifier
FROM pg_foreign_server s, pg_foreign_data_wrapper w, pg_authid u
WHERE w.oid = s.srvfdw
AND u.oid = s.srvowner
AND (pg_has_role(s.srvowner, 'USAGE')
OR has_server_privilege(s.oid, 'USAGE'));
/*
* 24.7
* FOREIGN_SERVER_OPTIONS view
*/
CREATE VIEW foreign_server_options AS
SELECT foreign_server_catalog,
foreign_server_name,
CAST((pg_options_to_table(s.srvoptions)).option_name AS sql_identifier) AS option_name,
CAST((pg_options_to_table(s.srvoptions)).option_value AS character_data) AS option_value
FROM _pg_foreign_servers s;
GRANT SELECT ON TABLE foreign_server_options TO PUBLIC;
/*
* 24.8
* FOREIGN_SERVERS view
*/
CREATE VIEW foreign_servers AS
SELECT foreign_server_catalog,
foreign_server_name,
foreign_data_wrapper_catalog,
foreign_data_wrapper_name,
foreign_server_type,
foreign_server_version,
authorization_identifier
FROM _pg_foreign_servers;
GRANT SELECT ON foreign_servers TO PUBLIC;
/* Base view for foreign tables */
CREATE VIEW _pg_foreign_tables AS
SELECT
CAST(current_database() AS sql_identifier) AS foreign_table_catalog,
CAST(n.nspname AS sql_identifier) AS foreign_table_schema,
CAST(c.relname AS sql_identifier) AS foreign_table_name,
t.ftoptions AS ftoptions,
CAST(current_database() AS sql_identifier) AS foreign_server_catalog,
CAST(srvname AS sql_identifier) AS foreign_server_name,
CAST(u.rolname AS sql_identifier) AS authorization_identifier
FROM pg_foreign_table t, pg_foreign_server s, pg_foreign_data_wrapper w,
pg_authid u, pg_namespace n, pg_class c
WHERE w.oid = s.srvfdw
AND u.oid = c.relowner
AND (pg_has_role(c.relowner, 'USAGE')
OR has_table_privilege(c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER')
OR has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES'))
AND n.oid = c.relnamespace
AND c.oid = t.ftrelid
AND c.relkind = 'f'
AND s.oid = t.ftserver;
/*
* 24.9
* FOREIGN_TABLE_OPTIONS view
*/
CREATE VIEW foreign_table_options AS
SELECT foreign_table_catalog,
foreign_table_schema,
foreign_table_name,
CAST((pg_options_to_table(t.ftoptions)).option_name AS sql_identifier) AS option_name,
CAST((pg_options_to_table(t.ftoptions)).option_value AS character_data) AS option_value
FROM _pg_foreign_tables t;
GRANT SELECT ON TABLE foreign_table_options TO PUBLIC;
/*
* 24.10
* FOREIGN_TABLES view
*/
CREATE VIEW foreign_tables AS
SELECT foreign_table_catalog,
foreign_table_schema,
foreign_table_name,
foreign_server_catalog,
foreign_server_name
FROM _pg_foreign_tables;
GRANT SELECT ON foreign_tables TO PUBLIC;
/* Base view for user mappings */
CREATE VIEW _pg_user_mappings AS
SELECT um.oid,
um.umoptions,
um.umuser,
CAST(COALESCE(u.rolname,'PUBLIC') AS sql_identifier ) AS authorization_identifier,
s.foreign_server_catalog,
s.foreign_server_name,
s.authorization_identifier AS srvowner
FROM pg_user_mapping um LEFT JOIN pg_authid u ON (u.oid = um.umuser),
_pg_foreign_servers s
WHERE s.oid = um.umserver;
/*
* 24.13
* USER_MAPPING_OPTIONS view
*/
CREATE VIEW user_mapping_options AS
SELECT authorization_identifier,
foreign_server_catalog,
foreign_server_name,
CAST(opts.option_name AS sql_identifier) AS option_name,
CAST(CASE WHEN (umuser <> 0 AND authorization_identifier = current_user)
OR (umuser = 0 AND pg_has_role(srvowner, 'USAGE'))
OR (SELECT rolsuper FROM pg_authid WHERE rolname = current_user)
THEN opts.option_value
ELSE NULL END AS character_data) AS option_value
FROM _pg_user_mappings um,
pg_options_to_table(um.umoptions) opts;
GRANT SELECT ON user_mapping_options TO PUBLIC;
/*
* 24.14
* USER_MAPPINGS view
*/
CREATE VIEW user_mappings AS
SELECT authorization_identifier,
foreign_server_catalog,
foreign_server_name
FROM _pg_user_mappings;
GRANT SELECT ON user_mappings TO PUBLIC;
| true |
4c921759d42d71dce5a9cf9b2c8bd52aff30365d | SQL | leithergit/AVPlayerActiveX | /screencut_position.sql | UTF-8 | 2,872 | 2.59375 | 3 | [] | no_license | /*
Navicat MySQL Data Transfer
Source Server : 192.168.1.125_3406
Source Server Version : 50527
Source Host : 192.168.1.125:3406
Source Database : vms
Target Server Type : MYSQL
Target Server Version : 50527
File Encoding : 65001
Date: 2017-08-16 15:42:52
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for screencut_position
-- ----------------------------
DROP TABLE IF EXISTS `screencut_position`;
CREATE TABLE `screencut_position` (
`cameraID` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`left` int(4) DEFAULT NULL,
`top` int(4) DEFAULT NULL,
`right` int(4) DEFAULT NULL,
`bottom` int(4) DEFAULT NULL,
`spreadHeiMin` float(20,5) DEFAULT NULL,
`spreadHeiMax` float(20,5) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records of screencut_position
-- ----------------------------
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '3', '0', '47', '0.00000', '9.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '50', '0', '0', '0.00000', '9.00000');
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '11', '0', '39', '9.00000', '18.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '40', '0', '10', '9.00000', '18.00000');
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '20', '0', '30', '18.00000', '24.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '32', '0', '18', '18.00000', '24.00000');
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '28', '0', '22', '24.00000', '25.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '25', '0', '25', '24.00000', '25.00000');
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '19', '0', '31', '25.00000', '30.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '34', '0', '16', '25.00000', '30.00000');
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '27', '0', '23', '30.00000', '37.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '27', '0', '23', '30.00000', '37.00000');
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '32', '0', '18', '37.00000', '40.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '21', '0', '29', '37.00000', '40.00000');
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '42', '0', '8', '40.00000', '42.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '13', '0', '37', '40.00000', '42.00000');
INSERT INTO `screencut_position` VALUES ('3301061000266', '0', '50', '0', '0', '42.00000', '60.00000');
INSERT INTO `screencut_position` VALUES ('3301061000267', '0', '0', '0', '50', '42.00000', '60.00000');
| true |
da4045f8fbb4e7eaaf4853c537c21abc0399e883 | SQL | mParkesy/JavaWeb-VigorHealthTracker | /Health/studentdb.sql | UTF-8 | 4,394 | 3.03125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 12, 2018 at 11:45 PM
-- Server version: 10.1.30-MariaDB
-- PHP Version: 7.2.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `studentdb`
--
-- --------------------------------------------------------
--
-- Table structure for table `sleep`
--
CREATE TABLE `sleep` (
`sleepID` int(11) NOT NULL,
`userID` int(11) NOT NULL,
`bedTime` datetime NOT NULL,
`wakeTime` datetime NOT NULL,
`sleepGrade` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`userID` int(11) NOT NULL,
`username` varchar(40) NOT NULL,
`password` varchar(100) NOT NULL,
`firstname` varchar(40) NOT NULL,
`lastname` varchar(40) NOT NULL,
`gender` enum('m','f') NOT NULL,
`postcode` varchar(8) NOT NULL,
`nationality` varchar(40) NOT NULL,
`email` varchar(60) NOT NULL,
`height` double NOT NULL,
`dob` date NOT NULL,
`exerciseLevel` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`userID`, `username`, `password`, `firstname`, `lastname`, `gender`, `postcode`, `nationality`, `email`, `height`, `dob`, `exerciseLevel`) VALUES
(1, 'parkesy', '81dc9bdb52d04dc20036dbd8313ed055', 'Matt', 'Parkes', 'm', 'NR59NZ', 'belarusian', 'matt.parkes@outlook.com', 186.5, '1996-10-10', 1.375),
(2, 'dsaiuf', '81dc9bdb52d04dc20036dbd8313ed055', 'hi', 'yo', 'f', 'dsfsdfds', 'barbadian', 'matt.parkes@outlook.com', 232, '0000-00-00', 1),
(4, 'asdasdasd', '202cb962ac59075b964b07152d234b70', 'dad', 'dad', 'f', 'pe29 gkn', '', 'asdasd@Asdasd.com', 1, '0000-00-00', 1),
(7, 'kappa1', '202cb962ac59075b964b07152d234b70', 'mum', 'mum', 'm', 'asdasd', 'barbudans', 'asd@asd.com', 1, '0000-00-00', 1),
(9, 'adasd', '202cb962ac59075b964b07152d234b70', 'dsedcqdf', 'fsdfsd', 'm', 'asdas', 'barbadian', 'asdas@dfsd.com', 323, '0000-00-00', 1),
(10, 'test', '202cb962ac59075b964b07152d234b70', 'qweq', 'qweqw', 'm', 'dasd', 'barbadian', 'asdas@fsdf.com', 23, '0000-00-00', 1),
(11, 'test2', '202cb962ac59075b964b07152d234b70', 'sdf', 'fgsdgd', 'm', 'tyjty', 'barbadian', 'fwef@dfgdf.com', 43, '0000-00-00', 1),
(12, 'parkesy2', '202cb962ac59075b964b07152d234b70', 'csdmkl', 'vmsdcfkl', 'm', 'cm233ng', 'albanian', 'wefjiowefh@sdfbh.com', 32, '0000-00-00', 1.725),
(13, 'test5', '36c5ac34a0dcf8de9344a6fb7a5c4648', 'Hello', 'there', 'm', 'sdfsd', 'american', 'matt.parkes@outlook.com', 182, '1996-10-10', 1.9);
-- --------------------------------------------------------
--
-- Table structure for table `weight`
--
CREATE TABLE `weight` (
`weightID` int(11) NOT NULL,
`userID` int(11) NOT NULL,
`weight` decimal(10,0) NOT NULL,
`date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `weight`
--
INSERT INTO `weight` (`weightID`, `userID`, `weight`, `date`) VALUES
(2, 1, '90', '2018-03-16'),
(8, 1, '82', '2018-03-22'),
(9, 1, '84', '2018-03-07'),
(12, 1, '82', '2018-03-18'),
(13, 1, '84', '2018-03-24'),
(14, 1, '85', '2018-03-25'),
(15, 13, '100', '2018-03-10');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `sleep`
--
ALTER TABLE `sleep`
ADD PRIMARY KEY (`sleepID`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`userID`),
ADD UNIQUE KEY `username` (`username`);
--
-- Indexes for table `weight`
--
ALTER TABLE `weight`
ADD PRIMARY KEY (`weightID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `sleep`
--
ALTER TABLE `sleep`
MODIFY `sleepID` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `userID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT for table `weight`
--
ALTER TABLE `weight`
MODIFY `weightID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
94ea1ce88181f35fdac62c8e1f934cc14d699c5a | SQL | chaesiong/rtp-database | /production/SYSTEM/tables/logmnr_container$.sql | UTF-8 | 832 | 2.609375 | 3 | [] | no_license | CREATE TABLE "SYSTEM"."LOGMNR_CONTAINER$" SHARING=METADATA
( "OBJ#" NUMBER NOT NULL ENABLE,
"CON_ID#" NUMBER NOT NULL ENABLE,
"DBID" NUMBER NOT NULL ENABLE,
"CON_UID" NUMBER NOT NULL ENABLE,
"CREATE_SCNWRP" NUMBER NOT NULL ENABLE,
"CREATE_SCNBAS" NUMBER NOT NULL ENABLE,
"FLAGS" NUMBER,
"STATUS" NUMBER NOT NULL ENABLE,
"LOGMNR_UID" NUMBER(22,0),
"LOGMNR_FLAGS" NUMBER(22,0),
"VSN" NUMBER,
"FED_ROOT_CON_ID#" NUMBER
)
PARTITION BY RANGE ("LOGMNR_UID")
(PARTITION "P_LESSTHAN100" VALUES LESS THAN (100) ) ;
ALTER TABLE "SYSTEM"."LOGMNR_CONTAINER$" ADD CONSTRAINT "LOGMNR_CONTAINER$_PK" PRIMARY KEY ("LOGMNR_UID", "OBJ#") DISABLE;
CREATE INDEX "SYSTEM"."LOGMNR_I1CONTAINER$" ON "SYSTEM"."LOGMNR_CONTAINER$" ("LOGMNR_UID", "CON_ID#")
LOCAL
(PARTITION "P_LESSTHAN100" ) ;
| true |
db7adbf30c2de34f952995e0bf8e8311acd50243 | SQL | 16pxdesign/oracle-category-tree | /001-addTASK.sql | UTF-8 | 623 | 3.34375 | 3 | [
"MIT"
] | permissive | create definer = admin@`%` procedure addTASK(IN name varchar(200), IN parent int unsigned, IN parentbyname varchar(200))
begin
declare cat_id int unsigned;
if parentbyname is not null then
select id into parent
from aaaPLAN.TASK c
where c.name = parentbyname;
end if;
Insert INTO aaaPLAN.TASK (name) VALUES (name);
select LAST_INSERT_ID() into cat_id;
INSERT INTO aaaPLAN.TASKTREE(parent_id, child_id, depth) VALUES(cat_id,cat_id,0);
if parent is not null then
INSERT INTO aaaPLAN.TASKTREE(parent_id, child_id, depth)
SELECT parent_id, cat_id, depth+1 from aaaPLAN.TASKTREE WHERE child_id = parent;
end if;
end;
| true |
d8fe916ef6e577b692ddbe695631b3e6751ceeaf | SQL | decosmi/enroll | /database/01_initial.sql | UTF-8 | 2,494 | 3.40625 | 3 | [] | no_license | DROP TABLE IF EXISTS student_guardian;
DROP TABLE IF EXISTS school_admin;
DROP TABLE IF EXISTS guardians;
DROP TABLE IF EXISTS emergency;
DROP TABLE IF EXISTS student_emergency;
DROP TABLE IF EXISTS students;
DROP TABLE IF EXISTS teacher;
CREATE TABLE teacher (
id serial PRIMARY KEY,
first_name text,
last_name text
);
ALTER TABLE teacher OWNER TO school;
CREATE TABLE guardians (
id serial PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
id_token text NOT NULL,
home_address text,
home_city text,
home_state text,
home_zip integer,
email text,
cell_phone text,
home_phone text,
work_phone text,
work_name text,
work_address text,
work_city text,
work_state text,
work_zip text,
work_email text
);
ALTER TABLE guardians OWNER TO school;
CREATE TABLE students (
id serial PRIMARY KEY,
first_name text NOT NULL,
middle_name text,
last_name text,
birthdate text,
gender text,
social_security text,
race_ethnicity text,
home_address text,
home_city text,
home_state text,
home_zip integer,
phone text,
teacher integer,
CONSTRAINT fk_from_teacher_to_students
FOREIGN KEY (teacher)
REFERENCES teacher(id)
);
ALTER TABLE students OWNER TO school;
CREATE TABLE student_guardian (
id serial PRIMARY KEY,
student_first text,
student_id integer,
guardian_id integer,
rel_to_student text,
CONSTRAINT fk_from_students_to_student_guardian
FOREIGN KEY (student_id)
REFERENCES students(id),
CONSTRAINT fk_from_guardians_to_student_guardians
FOREIGN KEY (guardian_id)
REFERENCES guardians(id)
);
ALTER TABLE student_guardian OWNER TO school;
CREATE TABLE emergency (
id serial PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL,
email text,
cell_phone integer,
home_phone integer,
work_phone integer,
work_name text,
work_address text
);
ALTER TABLE emergency OWNER TO school;
CREATE TABLE student_emergency (
id serial PRIMARY KEY,
student_id integer,
contact_id integer,
CONSTRAINT fk_from_students_to_ec
FOREIGN KEY (student_id)
REFERENCES students(id),
CONSTRAINT fk_from_ec_to_student_emergency
FOREIGN KEY (contact_id)
REFERENCES student_emergency(id)
);
ALTER TABLE student_emergency OWNER TO school;
CREATE TABLE school_admin (
id serial PRIMARY KEY,
first_name text,
last_name text
);
ALTER TABLE school_admin OWNER TO school;
| true |
b80f220790acf6048f69910a261bd0f8853fad26 | SQL | rayailieva/Database-Basics---MySQL | /08.Exams/exam/p11.ExtractAllEducationalMissions.sql | UTF-8 | 245 | 4 | 4 | [] | no_license | SELECT p.name AS 'planet_name',
s.name AS 'spaceport_name'
FROM planets AS p
JOIN spaceports AS s
ON p.id = s.planet_id
JOIN journeys AS j
ON s.id = j.destination_spaceport_id
WHERE j.purpose = 'Educational'
ORDER BY `spaceport_name` DESC; | true |
35d3f7f19f558296f27f2890b9675239dbc55f4e | SQL | Rendanic/SQL-Zauberkasten | /sql/xplan/dplansid.sql | UTF-8 | 597 | 3.0625 | 3 | [] | no_license | --
-- Thorsten Bruhns (Thorsten.Bruhns@opitz-consulting.de)
-- $Id: dplansid.sql 244 2010-11-14 14:35:23Z tbr $
--
-- display plan for running sql on session with SID
--
-- Parameter 1: SID
set echo off
set verify off
set feedback off
variable SQL_ID varchar2(20)
variable SQL_CHILD_NUMBER number
begin
select SQL_ID
,SQL_CHILD_NUMBER
into :SQL_ID
,:SQL_CHILD_NUMBER
from v$session
where sid = &&1;
end;
/
set feedback on
set pages 2000
set lines 200
set trimspool on
column PLAN_TABLE_OUTPUT format a200
select * from table(dbms_xplan.DISPLAY_CURSOR(:SQL_ID, :SQL_CHILD_NUMBER, 'ALL'));
| true |
bc20d29ecb35c2bbe288de86d64a3950f4f42c7f | SQL | allwaysoft/Oracle-1 | /AWR_statspack_exemplos/instalacao_statspack.sql | UTF-8 | 1,459 | 3.375 | 3 | [] | no_license | -- verificar se existe algum snapshot do statspack
select name, snap_id, to_char(snap_time, 'DD/MM/YYYY HH24:MI:SS') "Snapshot Time" from stats$snapshot,v$database;
-- cria um tablespace próprio para o statspack, não é necessário mas é recomendado
create tablespace PERFSTAT datafile '/home/oracle/app/oracle/oradata/orcl/perfstat.dbf' size 50M autoextend on next 50M maxsize 500M;
-- No oracle 12c para instalar o statspack no CDB é necessário alterar uma variável
alter session set "_oracle_script"=true;
-- instalação do statspack executar o script spcreate.sql que está dentro do oracle home conforme caminho abaixo
@?/rdbms/admin/spcreate.sql
-- alterando a senha caso necessário
alter user perfstat identified by oracle;
-- depois de criar os objetos que serão utilizados é recomendado coletar as estatisticas
exec dbms_stats.gather_schema_stats('PERFSTAT');
-- após estas etapas logar com o usuário perfstat e gerar o primeiro snapshot além de criar a job parar gera automáticamente os snaps
-- sqlplus perfstat/oracle
exec statspack.snap;
@?/rdbms/admin/spauto.sql
-- verificar se a job realmente foi criada
alter session set nls_date_format='dd/mm/yyyy hh24:mi:ss';
select job, what, LAST_DATE, NEXT_DATE, TOTAL_TIME, BROKEN, FAILURES from dba_jobs where SCHEMA_USER='PERFSTAT';
-- para gerar o relatório basta executar o script abaixo, lembrando que é necessário pelo menos 2 snaps para isto
@?/rdbms/admin/spreport.sql
| true |
69833e39503b2c786b2867f77d8a77bf9d83fd8c | SQL | Haoxi-Sun/COSC344-Database | /Lab6/q20.sql | UTF-8 | 160 | 3.34375 | 3 | [] | no_license | SELECT *
FROM orders outers
WHERE amt > (
SELECT AVG(amt)
FROM orders inners
WHERE outers.cnum = inners.cnum
);
| true |
81a80a113429f522df373aa2549e872d69931df8 | SQL | olseason/SQL | /Ex/Ex02.sql | UTF-8 | 4,553 | 4.3125 | 4 | [] | no_license | --null
select first_name, salary, commission_pct, salary * commission_pct
from employees
where salary between 13000 and 15000;
select first_name, salary, commission_pct
from employees
where commission_pct is not null;
select first_name, salary, commission_pct
from employees
where commission_pct is null;
--예제) 커미션비율이 있는 사원의 이름과 연봉 커미션비율을 출력
select first_name, commission_pct
from employees
where commission_pct is not null;
--예제) 담당매니저가 없고 커미션비율이 없는 직원의 이름을 출력
SELECT first_name
from employees
where commission_pct is null
and manager_id is null;
--ordrer by
select first_name, salary
from employees
order by salary desc; --내림차순
select first_name, salary
from employees
order by salary asc; --오름차순 \\
select first_name, salary
from employees
order by salary asc, first_name asc; --1순위 급여 오름차순. 급여가 동률일 때 사용
--예제) 부서번호를 오름차순으로 정렬하고 부서번호, 급여, 이름을 출력
select department_id, salary, first_name
from employees
order by department_id asc;
--예제) 급여가 10000이상인 이름과 급여가 큰 직원부터 출력
select first_name, salary
from employees
where salary >= 10000
order by salary desc;
--예제) 부서번호를 오름차순으로 정렬하고 부서번호가 같으면 급여가 높은 사람부터 부서번호, 급여, 이름 출력
select department_id, salary, first_name
from employees
order by department_id asc, salary desc;
--가상의 테이블 dual
select initcap('aaaa')
from dual;
/*단일행 함수*/
--문자함수 -initcap(컬럼명) 영어의 첫글자만 대문자로 출력, 나머지는 소문자
select email, initcap(email), department_id
from employees
where department_id = 100;
--문자함수 -lower(컬럼명) / upper(컬럼명) 입력되는 값을 전부 소문자/대문자로 변경
select first_name, lower(first_name), upper(first_name)
from employees
where department_id = 100;
--문자함수 -substr(컬럼명, 시작위치, 글자수)
select substr('abcdefg', 3, 4)
from dual;
select first_name, substr(first_name, 1, 3), substr(first_name, -3, 1)
from employees
where department_id = 100;
--문자함수 -lpad(컬럼명, 자리수, '채울문자') 왼쪽공백에 특별한 문자 / rpad() 오른쪽 공백
select first_name, lpad(first_name, 10, '*'),rpad(first_name, 10, '*')
from employees;
--문자함수 -replace(컬럼명, 문자1, 문자2) 컬럼명에서 문자1 -> 문자2로 바꿈
select first_name,
replace(first_name, 'a', '****')
from employees;
select first_name,
replace(first_name, 'a', '*'),
replace(first_name, substr(first_name, 2, 3), '***')
from employees
where department_id = 100;
/*숫자함수*/
--round(숫자, 출력을 원하는 자리수) 반올림
select round(123.346, 2),
round(123.346, 0),
round(123.346, -1)
from dual;
--turn 숫자의 버림을 하는 함수
select trunc(123.346, 2),
trunc(123.346, 0),
round(123.346, -1)
from dual;
/*단일행 함수*/
--abs
select abs(-5)
from dual;
/*날짜함수*/
--sysdate
select sysdate
from dual;
--monts_between
select MONTHS_BETWEEN(SYSDATE,hire_date)
from employees
where department_id = 110;
/*변환함수*/
--to_char() 숫자->문자열
select first_name, salary*12, to_char(salary*12, '$999,999.99')
from employees
where department_id = 100;
select to_char(9876, '99999'),
to_char(9876, '099999'),
to_char(9876, '$9999'),
to_char(9876, '9999.99'),
to_char(987654321, '999,999,999'),
to_char(987654321, '999,999,999,999')
from dual;
--to_char() 날짜->문자열
select sysdate,
to_char(sysdate, 'hh24: mi:ss'),
to_char(sysdate, 'yyyy"년"-mm"월"-dd"일"'),
to_char(sysdate, 'dd'),
to_char(sysdate, 'yyyy'),
to_char(sysdate, 'yy'),
to_char(sysdate, 'mm'),
to_char(sysdate, 'month'),
to_char(sysdate, 'dd'),
to_char(sysdate, 'day'),
to_char(sysdate, 'hh'),
to_char(sysdate, 'hh24'),
to_char(sysdate, 'mi'),
to_char(sysdate, 'ss')
from dual;
--nvl() nvl2()
select first_name, commission_pct, nvl(commission_pct, 0)
from employees;
select first_name,
commission_pct,
nvl(commission_pct, 0),
nvl2(commission_pct, 1, 0)
from employees; | true |
061a2ea1bd014bde029b5a954880742df43de50a | SQL | dhanarJkusuma/guardian | /migration/sql/mysql_migration_index.up.sql | UTF-8 | 767 | 2.859375 | 3 | [] | no_license | -- create index
CREATE UNIQUE INDEX `guard_user_email_idx` ON guard_user(email);
CREATE UNIQUE INDEX `guard_user_username_idx` ON guard_user(username);
CREATE UNIQUE INDEX `guard_permission_route_method_idx` ON guard_permission(route, method);
CREATE UNIQUE INDEX `guard_permission_name_idx` ON guard_permission(name);
CREATE UNIQUE INDEX `guard_role_name_idx` ON guard_role(name);
CREATE UNIQUE INDEX `guard_user_role_role_user_idx` on guard_user_role (role_id, user_id);
CREATE UNIQUE INDEX `guard_role_permission_role_permission_idx` on guard_role_permission (role_id, permission_id);
CREATE UNIQUE INDEX `guard_role_guard_rule_idx` ON guard_rule (name, rule_type, parent_id);
CREATE INDEX `guard_role_guard_rule_checker_idx` ON guard_rule (rule_type, parent_id);
| true |
09c50d07250d3fac7b3ac487017d34a296163795 | SQL | ColdHeat/piwheels | /piwheels/initdb/sql/update_piwheels_0.11_to_0.12.sql | UTF-8 | 846 | 3.515625 | 4 | [
"MIT",
"BSD-3-Clause"
] | permissive | UPDATE configuration SET version = '0.12';
CREATE TABLE searches (
package VARCHAR(200) NOT NULL,
accessed_by INET NOT NULL,
accessed_at TIMESTAMP NOT NULL,
arch VARCHAR(100) DEFAULT NULL,
distro_name VARCHAR(100) DEFAULT NULL,
distro_version VARCHAR(100) DEFAULT NULL,
os_name VARCHAR(100) DEFAULT NULL,
os_version VARCHAR(100) DEFAULT NULL,
py_name VARCHAR(100) DEFAULT NULL,
py_version VARCHAR(100) DEFAULT NULL,
CONSTRAINT packages_package_fk FOREIGN KEY (package)
REFERENCES packages (package) ON DELETE CASCADE
);
CREATE INDEX searches_package ON searches(package);
CREATE INDEX searches_accessed_at ON searches(accessed_at DESC);
GRANT SELECT,INSERT ON searches TO {username};
COMMIT;
| true |
3a85842ff96dc2183d124728143e3bf1f08f2f5c | SQL | Ronihe/input-list | /back-end/schema.sql | UTF-8 | 198 | 2.71875 | 3 | [] | no_license | DROP DATABASE if exists inputs_db;
CREATE DATABASE inputs_db;
\c inputs_db
CREATE TABLE inputs
(
id SERIAL PRIMARY KEY,
input TEXT NOT NULL,
date_posted DATE NOT NULL DEFAULT CURRENT_DATE
); | true |
815a0830370bbf80e6d953dbaad17744bbd298d6 | SQL | tgq52298/test | /application/vote/install/install.sql | UTF-8 | 13,264 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | INSERT INTO `qb_config` (`id`, `type`, `title`, `c_key`, `c_value`, `form_type`, `options`, `ifsys`, `htmlcode`, `c_descrip`, `list`, `sys_id`) VALUES('', -1, 'SEO标题', 'mseo_title', '', 'text', '', 0, '', '', 100, 4);
INSERT INTO `qb_config` (`id`, `type`, `title`, `c_key`, `c_value`, `form_type`, `options`, `ifsys`, `htmlcode`, `c_descrip`, `list`, `sys_id`) VALUES('', -1, 'SEO优化关键字keywords', 'mseo_keyword', '', 'text', '', 0, '', '', 99, 4);
INSERT INTO `qb_config` (`id`, `type`, `title`, `c_key`, `c_value`, `form_type`, `options`, `ifsys`, `htmlcode`, `c_descrip`, `list`, `sys_id`) VALUES('', -1, 'SEO优化描述description', 'mseo_description', '', 'text', '', 0, '', '', 98, 4);
-- --------------------------------------------------------
--
-- 表的结构 `qb_vote_category`
--
DROP TABLE IF EXISTS `qb_vote_category`;
CREATE TABLE IF NOT EXISTS `qb_vote_category` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pid` int(10) NOT NULL,
`name` varchar(50) NOT NULL,
`list` int(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `pid` (`pid`),
KEY `list` (`list`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='辅栏目' AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- 表的结构 `qb_vote_content`
--
DROP TABLE IF EXISTS `qb_vote_content`;
CREATE TABLE IF NOT EXISTS `qb_vote_content` (
`id` int(8) unsigned NOT NULL AUTO_INCREMENT,
`mid` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '模型ID',
`uid` int(8) NOT NULL,
PRIMARY KEY (`id`),
KEY `mid` (`mid`),
KEY `uid` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='内容索引表' AUTO_INCREMENT=20 ;
--
-- 转存表中的数据 `qb_vote_content`
--
-- INSERT INTO `qb_vote_content` VALUES ('20','1','1');
-- INSERT INTO `qb_vote_content` VALUES ('21','1','1');
-- --------------------------------------------------------
--
-- 表的结构 `qb_cms_content1`
--
-- 投票模型内容表
DROP TABLE IF EXISTS `qb_vote_content1`;
CREATE TABLE `qb_vote_content1` (
`id` int(8) unsigned NOT NULL AUTO_INCREMENT,
`mid` smallint(4) unsigned NOT NULL DEFAULT '0' COMMENT '模型ID',
`fid` mediumint(6) unsigned NOT NULL DEFAULT '0' COMMENT '栏目ID',
`title` varchar(256) NOT NULL DEFAULT '' COMMENT '标题',
`ispic` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否带组图',
`uid` mediumint(7) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
`view` mediumint(7) unsigned NOT NULL DEFAULT '0' COMMENT '浏览量',
`status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态:0未审 1已审 2推荐',
`agree` mediumint(5) NOT NULL DEFAULT '0' COMMENT '点赞',
`replynum` mediumint(5) unsigned NOT NULL DEFAULT '0' COMMENT '评论数',
`create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`update_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '修改时间',
`list` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序值',
`picurl` text NOT NULL COMMENT '封面图',
`content` text NOT NULL COMMENT '文章内容',
`province_id` mediumint(5) NOT NULL COMMENT '省会ID',
`city_id` mediumint(5) NOT NULL COMMENT '城市ID',
`zone_id` mediumint(5) NOT NULL COMMENT '县级市或所在区ID',
`street_id` mediumint(5) NOT NULL COMMENT '乡镇或区域街道ID',
`ext_sys` smallint(5) NOT NULL COMMENT '扩展字段,关联的系统',
`ext_id` int(7) NOT NULL COMMENT '扩展字段,关联的ID',
`mobphone` varchar(12) DEFAULT NULL COMMENT '联系电话',
PRIMARY KEY (`id`),
KEY `mid` (`mid`),
KEY `fid` (`fid`),
KEY `view` (`view`),
KEY `status` (`status`),
KEY `list` (`list`),
KEY `ispic` (`ispic`),
KEY `province_id` (`province_id`),
KEY `city_id` (`city_id`),
KEY `ext_id` (`ext_id`,`ext_sys`),
KEY `ext_id_2` (`ext_id`,`ext_sys`)
) ENGINE=MyISAM AUTO_INCREMENT=42 DEFAULT CHARSET=utf8 COMMENT='投票模型模型表';
--
-- 转存表中的数据 `qb_cms_content1`
--
-- INSERT INTO `qb_vote_content1` VALUES ('20','1','1','连锁品牌招牌','1','1','10','1','14','0','1530608032','0','1530608032','uploads/images/20180703/1_20180703165348e12e4.jpeg','<p>连锁品牌招牌<br></p>','0','0','0','0','0','0',NULL);
-- INSERT INTO `qb_vote_content1` VALUES ('21','1','1','城市便捷招牌','1','1','22','1','2','0','1530609565','0','1530609565','uploads/images/20180703/1_20180703171920584dc.jpeg','<p><span style=\"font-size: 16px;\">近5千平花园式厂房,17年发光字、标识牌老厂。通过ISO9001-2015质量管理体系认证;通过ISO1400-2015环境管理体系认证;广东省标识行业协会推荐单位;广东省重合同守信用企业;上市公司源材料产业链,匠心打造近100家知名企业成功案例,我们将以更开放务实的姿态,迎接五湖四海的客户!全国服务热线:4006-255-229 </span><br></p>','0','0','0','0','0','0',NULL);
-- --------------------------------------------------------
--
-- 表的结构 `qb_vote_field`
--
DROP TABLE IF EXISTS `qb_vote_field`;
CREATE TABLE `qb_vote_field` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '字段名称',
`name` varchar(32) NOT NULL,
`title` varchar(60) NOT NULL DEFAULT '' COMMENT '字段标题',
`type` varchar(32) NOT NULL DEFAULT '' COMMENT '字段类型',
`field_type` varchar(128) NOT NULL DEFAULT '' COMMENT '字段定义',
`value` text COMMENT '默认值',
`options` text COMMENT '额外选项',
`about` varchar(256) NOT NULL DEFAULT '' COMMENT '提示说明',
`show` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '是否显示',
`mid` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '所属模型id',
`ajax_url` varchar(256) NOT NULL DEFAULT '' COMMENT '联动下拉框ajax地址',
`next_items` varchar(256) NOT NULL DEFAULT '' COMMENT '联动下拉框的下级下拉框名,多个以逗号隔开',
`param` varchar(32) NOT NULL DEFAULT '' COMMENT '联动下拉框请求参数名',
`format` varchar(32) NOT NULL DEFAULT '' COMMENT '格式,用于格式文本',
`table` varchar(32) NOT NULL DEFAULT '' COMMENT '表名,只用于快速联动类型',
`level` tinyint(2) unsigned NOT NULL DEFAULT '2' COMMENT '联动级别,只用于快速联动类型',
`key` varchar(32) NOT NULL DEFAULT '' COMMENT '键字段,只用于快速联动类型',
`option` varchar(32) NOT NULL DEFAULT '' COMMENT '值字段,只用于快速联动类型',
`pid` varchar(32) NOT NULL DEFAULT '' COMMENT '父级id字段,只用于快速联动类型',
`list` int(10) NOT NULL DEFAULT '100' COMMENT '排序',
`listshow` tinyint(1) NOT NULL COMMENT '是否在列表显示',
`ifsearch` tinyint(1) NOT NULL COMMENT '是否作为搜索字段',
`ifmust` tinyint(1) NOT NULL COMMENT '是否必填项',
`nav` varchar(30) NOT NULL COMMENT '分组名称',
`input_width` varchar(7) NOT NULL COMMENT '输入表单宽度',
`input_height` varchar(7) NOT NULL COMMENT '输入表单高度',
`unit` varchar(20) NOT NULL COMMENT '单位名称',
`match` varchar(150) NOT NULL COMMENT '表单正则匹配',
`css` varchar(20) NOT NULL COMMENT '表单CSS类名',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=53 DEFAULT CHARSET=utf8 COMMENT='文档字段表';
--
-- 转存表中的数据 `qb_vote_field`
--
INSERT INTO `qb_vote_field` VALUES ('10','title','选项名称','text','varchar(256) NOT NULL','','','','0','1','','','','','','2','','','','100','1','1','1','','','','','','');
INSERT INTO `qb_vote_field` VALUES ('11','picurl','封面图','images','text NOT NULL','','','','0','1','','','','','','2','','','','100','0','0','0','','','','','','');
INSERT INTO `qb_vote_field` VALUES ('12','content','选项描述','ueditor','text NOT NULL','','','','0','1','','','','','','2','','','','98','0','0','0','','','','','','');
INSERT INTO `qb_vote_field` VALUES ('52','mobphone','联系电话','text','varchar(12)','','','联系电话,获奖后方便联系','1','1','','','','','','2','','','','99','1','0','0','','','','','','');
-- --------------------------------------------------------
--
-- 表的结构 `qb_vote_info`
--
DROP TABLE IF EXISTS `qb_vote_info`;
CREATE TABLE `qb_vote_info` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`aid` int(11) NOT NULL COMMENT '内容ID',
`cid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '辅栏目ID',
`list` int(10) NOT NULL COMMENT '排序值',
PRIMARY KEY (`id`),
KEY `mid` (`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='内容索引表';
-- --------------------------------------------------------
--
-- 表的结构 `qb_vote_module`
--
DROP TABLE IF EXISTS `qb_vote_module`;
CREATE TABLE `qb_vote_module` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`keyword` varchar(32) NOT NULL DEFAULT '' COMMENT '区分符关键字',
`title` varchar(32) NOT NULL DEFAULT '' COMMENT '模型标题',
`layout` varchar(50) NOT NULL COMMENT '模板路径',
`icon` varchar(64) NOT NULL,
`list` int(10) NOT NULL DEFAULT '100' COMMENT '排序',
`create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`status` tinyint(2) unsigned NOT NULL DEFAULT '0' COMMENT '状态',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='模型表';
--
-- 转存表中的数据 `qb_vote_module`
--
INSERT INTO `qb_vote_module` VALUES ('1','','投票模型','','','100','1515221331','0');
-- --------------------------------------------------------
--
-- 表的结构 `qb_vote_sort`
--
DROP TABLE IF EXISTS `qb_vote_sort`;
CREATE TABLE `qb_vote_sort` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pid` int(10) NOT NULL,
`mid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '模型ID',
`name` varchar(50) NOT NULL COMMENT '投票项目名称',
`type` tinyint(2) NOT NULL DEFAULT '0' COMMENT '投票选项:0单选,1多选',
`limittime` int(10) NOT NULL DEFAULT '0' COMMENT '每次投票时间间隔,0不限,单位分钟',
`limitip` tinyint(2) NOT NULL DEFAULT '0' COMMENT '是否限制IP重复投票:0不限,1限制',
`forbidguestvote` tinyint(2) NOT NULL DEFAULT '0' COMMENT '是否禁止游客投票:0不限,1限制',
`repeatjoinvote` tinyint(2) NOT NULL DEFAULT '0' COMMENT '是否禁止重复报名:0不限,1限制',
`joinbegintime` int(10) NOT NULL DEFAULT '0' COMMENT '报名开始时间',
`joinendtime` int(10) NOT NULL DEFAULT '0' COMMENT '报名结束时间',
`begintime` int(10) NOT NULL DEFAULT '0' COMMENT '投票开始时间',
`endtime` int(10) NOT NULL DEFAULT '0' COMMENT '投票结束时间',
`description` text NOT NULL COMMENT '投票内容描述',
`list` int(10) NOT NULL,
`logo` varchar(50) NOT NULL COMMENT '封面图',
`template` varchar(255) NOT NULL COMMENT '模板',
`allowpost` varchar(100) NOT NULL COMMENT '允许发布信息的用户组',
`allowpostyz` varchar(100) NOT NULL COMMENT '允许报名自动通过审核的用户组',
`allowview` varchar(100) NOT NULL COMMENT '允许浏览内容的用户组',
`seo_title` varchar(255) NOT NULL COMMENT 'SEO标题',
`seo_keywords` varchar(255) NOT NULL COMMENT 'SEO关键字',
`seo_description` varchar(255) NOT NULL COMMENT 'SEO描述',
`ips` text NOT NULL COMMENT '已投票的IP',
PRIMARY KEY (`id`),
KEY `mid` (`mid`),
KEY `pid` (`pid`),
KEY `list` (`list`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='主栏目表';
-- INSERT INTO `qb_vote_sort` VALUES ('1','0','1','启达广告标识','1','0','0','1','0','1531125912','1531444449','1531015488','1532059033','近5千平花园式厂房,17年发光字、标识牌老厂。通过ISO9001-2015质量管理体系认证;通过ISO1400-2015环境管理体系认证;广东省标识行业协会推荐单位;广东省重合同守信用企业;上市公司源材料产业链,匠心打造近100家知名企业成功案例,我们将以更开放务实的姿态,迎接五湖四海的客户!全国服务热线:4006-255-229 \r\n','0','','','','','','','','127.0.0.10,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1,127.0.0.1');
--
-- 转存表中的数据 `qb_vote_member`
--
DROP TABLE IF EXISTS `qb_vote_member`;
CREATE TABLE `qb_vote_member` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`aid` int(7) NOT NULL COMMENT '投票选项ID',
`fid` int(7) NOT NULL COMMENT '投票项目ID',
`uid` int(7) NOT NULL COMMENT '投票用户ID',
`create_time` int(10) NOT NULL COMMENT '投票时间时间',
`ip` varchar(15) COLLATE utf8_bin NOT NULL COMMENT '投票所在IP',
`type` tinyint(2) NOT NULL DEFAULT '1' COMMENT '扩展字段,可拓展为1是投票',
PRIMARY KEY (`id`),
KEY `uid` (`uid`),
KEY `aid` (`aid`),
KEY `type` (`type`),
KEY `fid` (`fid`)
) ENGINE=MyISAM AUTO_INCREMENT=47 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='用户投票记录';
| true |
e28e9305cf612f217d080d4e21675f457810666e | SQL | mad-ann/Quiz_2020 | /Quiz_2020/quizz.sql | UTF-8 | 3,072 | 3.515625 | 4 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Gép: 127.0.0.1
-- Létrehozás ideje: 2020. Már 19. 17:36
-- Kiszolgáló verziója: 10.4.11-MariaDB
-- PHP verzió: 7.4.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Adatbázis: `quizz`
--
CREATE DATABASE IF NOT EXISTS `quizz` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
USE `quizz`;
-- --------------------------------------------------------
--
-- Tábla szerkezet ehhez a táblához `kategoria`
--
CREATE TABLE IF NOT EXISTS `kategoria` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nev` varchar(70) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
--
-- A tábla adatainak kiíratása `kategoria`
--
INSERT INTO `kategoria` (`id`, `nev`) VALUES
(1, 'Történelem');
-- --------------------------------------------------------
--
-- Tábla szerkezet ehhez a táblához `kerdesek`
--
CREATE TABLE IF NOT EXISTS `kerdesek` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`szoveg` varchar(70) NOT NULL,
`kategoria_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_kerdes_kat` (`kategoria_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Tábla szerkezet ehhez a táblához `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nev` varchar(70) NOT NULL,
`felhasznalonev` varchar(50) NOT NULL,
`password` varchar(35) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
--
-- A tábla adatainak kiíratása `users`
--
INSERT INTO `users` (`id`, `nev`, `felhasznalonev`, `password`) VALUES
(1, 'Boros Sándor', 'boros', '3411b893c1a200fdcaaf3dcd4b1d636d');
-- --------------------------------------------------------
--
-- Tábla szerkezet ehhez a táblához `valaszok`
--
CREATE TABLE IF NOT EXISTS `valaszok` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`kerdes_id` int(11) NOT NULL,
`valasz` varchar(50) NOT NULL,
`helyes` enum('igaz','hamis') NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_kerdes_valasz` (`kerdes_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Megkötések a kiírt táblákhoz
--
--
-- Megkötések a táblához `kerdesek`
--
ALTER TABLE `kerdesek`
ADD CONSTRAINT `fk_kerdes_kat` FOREIGN KEY (`kategoria_id`) REFERENCES `kategoria` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE;
--
-- Megkötések a táblához `valaszok`
--
ALTER TABLE `valaszok`
ADD CONSTRAINT `fk_kerdes_valasz` FOREIGN KEY (`kerdes_id`) REFERENCES `kerdesek` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
10904edd12b8504dcb12c549a09f395b110dec75 | SQL | chieh0613/462_Database_Project | /statistics_sql/0716002/best_movie_top5.sql | UTF-8 | 180 | 3.5 | 4 | [] | no_license | /*哪5年生產最多優秀(rating>=8)電影*/
SELECT m.year, count(*)
FROM all_gender al, movie m
where al.id=m.id and al.rating>8
GROUP BY m.year
ORDER BY count(*) DESC LIMIT 5; | true |
842f3a7e4654e0b6d68ff1837e049e02b7e815d3 | SQL | zefredz/claroline-packages | /modules/ICHELP/setup/install.sql | UTF-8 | 793 | 2.65625 | 3 | [] | no_license | /**
* $Id$
* Online Help Form
*
* @version ICHELP 0.8 $Revision$ - Claroline 1.11.5
* @copyright 2001-2013 Universite catholique de Louvain (UCL)
* @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE
* @package ICHELP
* @author Frederic Fervaille <frederic.fervaille@uclouvain.be>
*/
CREATE TABLE IF NOT EXISTS `__CL_MAIN__ichelp_log`(
ticketId VARCHAR(64) NOT NULL,
userId INT(11),
courseId VARCHAR(64),
submissionDate DATETIME,
userAgent TEXT,
urlOrigin TEXT,
userInfos TEXT,
issueDescription TEXT,
shortDescription VARCHAR(255),
mailSent BOOLEAN NOT NULL DEFAULT FALSE,
autoMailSent BOOLEAN NOT NULL DEFAULT FALSE,
status ENUM('pending','solved','closed') NOT NULL DEFAULT 'pending',
PRIMARY KEY(ticketId)
) ENGINE=MyISAM; | true |
4e2e130c7578c84f96fcc71e9aa6fb65958296bc | SQL | journeycruz/Password_Genie | /db/seeds.sql | UTF-8 | 371 | 2.90625 | 3 | [] | no_license | INSERT INTO UserNameAndPasswordDemo(UserId, UserPassword) VALUES ('John@gg.com', MD5('john123'));
(
U_Id int(10) unsigned NOT NULL AUTO_INCREMENT,
UserId varchar(255) DEFAULT NULL,
UserPassword varchar(255) DEFAULT NULL,
primary key(U_Id),
UNIQUE KEY `UserId` (`UserId`)
);
SELECT *from UserNameAndPasswordDemo where UserId='John@gg.com';
SELECT *from UserNameAndPasswordDemo; | true |
a94c1984ee12b704c68b90725f6ec87c9e0aff00 | SQL | sprokushev/Delphi | /MASTER/_DATABASE/Views/V_GD_VYP_READY.sql | UTF-8 | 2,688 | 2.8125 | 3 | [] | no_license | --
-- V_GD_VYP_READY (View)
--
CREATE OR REPLACE FORCE VIEW MASTER.V_GD_VYP_READY
(NAIM_GR, NAIM_PR, NORMOTGR, KOD_GR, TIP_OTGR,
KOD_NPR, EXPORT, TIP_OTGR_1, KOD_NPR_1, EXPORT_1,
PLAN_CIST, PLAN_VES, PLAN_CSOB, PLAN_VSOB, N_PL_C,
N_PL_V, N_PL_CS, N_PL_VS, D_PL_C, D_PL_V,
D_PL_CS, D_PL_VS, NORM_TOT, NORM_MPS, NORM_SOB,
KOD_GDPL, TIP_OTGR_2, KOD_NPR_2, EXPORT_2, KOD_GROTP,
GROTP, FACT_MON_C, FACT_MON_T, FACT_SUT_C, F_SOBC_SUT,
F_SOBC_MON, F_SOBV_MON, FACT_SUT_T)
AS
SELECT /*+ RULE */
kls_prod_gu12.NAME_GDPL AS naim_gr,
kls_prod.ABBR_NPR as naim_pr,
kls_prod.NORMOTGR,
kls_prod_gu12.ID AS kod_gr,
a."TIP_OTGR",a."KOD_NPR",a."EXPORT",
nvl(V_GD_VYP_GDPLAN.TIP_OTGR_1,0) AS TIP_OTGR_1,
nvl(V_GD_VYP_GDPLAN.KOD_NPR_1,0) AS KOD_NPR_1,
nvl(V_GD_VYP_GDPLAN.EXPORT_1,0) AS EXPORT_1,
nvl(V_GD_VYP_GDPLAN.PLAN_CIST,0) AS plan_cist,
nvl(V_GD_VYP_GDPLAN.PLAN_VES,0)AS PLAN_VES,
nvl(V_GD_VYP_GDPLAN.PLAN_CSOB,0) As PLAN_CSOB,
nvl(V_GD_VYP_GDPLAN.PLAN_VSOB,0) as PLAN_VSOB,
nvl(V_GD_VYP_GDPLAN.N_PL_C,0) as N_PL_C,
nvl(V_GD_VYP_GDPLAN.N_PL_V,0) As N_PL_V,
nvl(V_GD_VYP_GDPLAN.N_PL_CS,0) AS N_PL_CS,
nvl(V_GD_VYP_GDPLAN.N_PL_VS,0) AS N_PL_VS,
nvl(V_GD_VYP_GDPLAN.D_PL_C,0) AS D_PL_C,
nvl(V_GD_VYP_GDPLAN.D_PL_V,0) AS D_PL_V,
nvl(V_GD_VYP_GDPLAN.D_PL_CS,0) AS D_PL_CS,
nvl(V_GD_VYP_GDPLAN.D_PL_VS,0) AS D_PL_VS,
nvl(V_GD_VYP_GDPLAN.NORM_TOT,0) AS NORM_TOT,
nvl(V_GD_VYP_GDPLAN.NORM_MPS,0) as NORM_MPS,
nvl(V_GD_VYP_GDPLAN.NORM_SOB,0) AS NORM_SOB,
nvl(V_GD_VYP_GDPLAN.KOD_GDPL,0) As KOD_GDPL,
nvl(V_GD_VYP.TIP_OTGR_2,0) AS TIP_OTGR_2,
nvl(V_GD_VYP.KOD_NPR_2,0) AS KOD_NPR_2,
nvl(V_GD_VYP.EXPORT_2,0) AS EXPORT_2,
V_GD_VYP.KOD_GROTP AS KOD_GROTP,
V_GD_VYP.GROTP AS GROTP,
nvl(V_GD_VYP.FACT_MON_C,0) AS FACT_MON_C,
nvl(V_GD_VYP.FACT_MON_T,0) AS FACT_MON_T,
nvl(V_GD_VYP.FACT_SUT_C,0) AS FACT_SUT_C,
nvl(V_GD_VYP.F_SOBC_SUT,0) AS F_SOBC_SUT,
nvl(V_GD_VYP.F_SOBC_MON,0) AS F_SOBC_MON,
nvl(V_GD_VYP.F_SOBV_MON,0) AS F_SOBV_MON,
nvl(V_GD_VYP.FACT_SUT_T,0) AS FACT_SUT_T
FROM
(SELECT DISTINCT * FROM
(SELECT tip_otgr_2 AS tip_otgr,kod_npr_2 AS kod_npr, export_2 AS export FROM V_GD_VYP
UNION ALL
SELECT tip_otgr_1,kod_npr_1,export_1 FROM V_GD_VYP_GDPLAN)) a,V_GD_VYP_GDPLAN,V_GD_VYP,kls_prod,kls_prod_gu12
WHERE
a.tip_otgr=V_GD_VYP_GDPLAN.tip_otgr_1(+) and
a.kod_npr=V_GD_VYP_GDPLAN.kod_npr_1(+) and
a.export=V_GD_VYP_GDPLAN.export_1(+) and
a.tip_otgr=V_GD_VYP.tip_otgr_2(+) and
a.kod_npr=V_GD_VYP.kod_npr_2(+) and
a.export=V_GD_VYP.export_2(+) and
a.kod_npr=kls_prod.ID_NPR and
kls_prod.PROD_GU12_ID=kls_prod_gu12.ID
ORDER BY
TIP_OTGR,ORDER_GDPL,EXPORT;
| true |
1f41419f313f41a0438185ce7a57ef1fc14719bc | SQL | edjunior73/MBlabs-desafio | /prisma/migrations/20210618174918_db_att/migration.sql | UTF-8 | 244 | 2.671875 | 3 | [] | no_license | /*
Warnings:
- A unique constraint covering the columns `[name]` on the table `events` will be added. If there are existing duplicate values, this will fail.
*/
-- CreateIndex
CREATE UNIQUE INDEX "events.name_unique" ON "events"("name");
| true |
f164e07e9992a0b32374f185d53f472bcf5017d5 | SQL | kongyew/gpdb | /src/test/tinc/tincrepo/mpp/gpdb/tests/storage/filerep_end_to_end/ct/sql/ct_ao_alter_part_truncate_part.sql | UTF-8 | 7,004 | 3.296875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"PostgreSQL",
"LicenseRef-scancode-other-copyleft",
"metamail",
"BSD-3-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-other-permissive",
"ISC",
"Python-2.0",
"bzip2-1.0.6",
"LicenseRef-scancode-ssleay-windows",
"LicenseRef-scanco... | permissive | -- start_ignore
SET gp_create_table_random_default_distribution=off;
-- end_ignore
--
-- CT AO TABLE 1
--
CREATE TABLE ct_ao_alter_part_truncate_part1 (
unique1 int4,
unique2 int4
) with ( appendonly='true') partition by range (unique1)
( partition aa start (0) end (500) every (100), default partition default_part );
CREATE TABLE ct_ao_alter_part_truncate_part1_A (
unique1 int4,
unique2 int4) with ( appendonly='true');
--
-- Insert few records into the table
--
insert into ct_ao_alter_part_truncate_part1 values ( generate_series(5,50),generate_series(15,60));
insert into ct_ao_alter_part_truncate_part1_A values ( generate_series(1,10),generate_series(21,30));
--
-- select from the Table
--
select count(*) from ct_ao_alter_part_truncate_part1;
--
-- CT AO TABLE 2
--
CREATE TABLE ct_ao_alter_part_truncate_part2 (
unique1 int4,
unique2 int4
) with ( appendonly='true') partition by range (unique1)
( partition aa start (0) end (500) every (100), default partition default_part );
CREATE TABLE ct_ao_alter_part_truncate_part2_A (
unique1 int4,
unique2 int4) with ( appendonly='true');
--
-- Insert few records into the table
--
insert into ct_ao_alter_part_truncate_part2 values ( generate_series(5,50),generate_series(15,60));
insert into ct_ao_alter_part_truncate_part2_A values ( generate_series(1,10),generate_series(21,30));
--
-- select from the Table
--
select count(*) from ct_ao_alter_part_truncate_part2;
--
-- CT AO TABLE 3
--
CREATE TABLE ct_ao_alter_part_truncate_part3 (
unique1 int4,
unique2 int4
) with ( appendonly='true') partition by range (unique1)
( partition aa start (0) end (500) every (100), default partition default_part );
CREATE TABLE ct_ao_alter_part_truncate_part3_A (
unique1 int4,
unique2 int4) with ( appendonly='true');
--
-- Insert few records into the table
--
insert into ct_ao_alter_part_truncate_part3 values ( generate_series(5,50),generate_series(15,60));
insert into ct_ao_alter_part_truncate_part3_A values ( generate_series(1,10),generate_series(21,30));
--
-- select from the Table
--
select count(*) from ct_ao_alter_part_truncate_part3;
--
-- CT AO TABLE 4
--
CREATE TABLE ct_ao_alter_part_truncate_part4 (
unique1 int4,
unique2 int4
) with ( appendonly='true') partition by range (unique1)
( partition aa start (0) end (500) every (100), default partition default_part );
CREATE TABLE ct_ao_alter_part_truncate_part4_A (
unique1 int4,
unique2 int4) with ( appendonly='true');
--
-- Insert few records into the table
--
insert into ct_ao_alter_part_truncate_part4 values ( generate_series(5,50),generate_series(15,60));
insert into ct_ao_alter_part_truncate_part4_A values ( generate_series(1,10),generate_series(21,30));
--
-- select from the Table
--
select count(*) from ct_ao_alter_part_truncate_part4;
--
-- CT AO TABLE 5
--
CREATE TABLE ct_ao_alter_part_truncate_part5 (
unique1 int4,
unique2 int4
) with ( appendonly='true') partition by range (unique1)
( partition aa start (0) end (500) every (100), default partition default_part );
CREATE TABLE ct_ao_alter_part_truncate_part5_A (
unique1 int4,
unique2 int4) with ( appendonly='true');
--
-- Insert few records into the table
--
insert into ct_ao_alter_part_truncate_part5 values ( generate_series(5,50),generate_series(15,60));
insert into ct_ao_alter_part_truncate_part5_A values ( generate_series(1,10),generate_series(21,30));
--
-- select from the Table
--
select count(*) from ct_ao_alter_part_truncate_part5;
--
-- ALTER SYNC1 AO
--
--
-- Truncate Partition
--
alter table sync1_ao_alter_part_truncate_part4 truncate partition for (rank(1));
--
-- Insert few records into the table
--
insert into sync1_ao_alter_part_truncate_part4 values ( generate_series(5,50),generate_series(15,60));
insert into sync1_ao_alter_part_truncate_part4_A values ( generate_series(1,10),generate_series(21,30));
--
-- Alter the table set distributed by
--
Alter table sync1_ao_alter_part_truncate_part4 set with ( reorganize='true') distributed by (unique2);
--
-- select from the Table
--
select count(*) from sync1_ao_alter_part_truncate_part4;
--
-- Truncate default partition
--
alter table sync1_ao_alter_part_truncate_part4 truncate default partition;
--
-- Insert few records into the table
--
insert into sync1_ao_alter_part_truncate_part4 values ( generate_series(5,50),generate_series(15,60));
insert into sync1_ao_alter_part_truncate_part4_A values ( generate_series(1,10),generate_series(21,30));
--
-- select from the Table
--
select count(*) from sync1_ao_alter_part_truncate_part4;
--
-- ALTER CK_SYNC1 AO
--
--
-- Truncate Partition
--
alter table ck_sync1_ao_alter_part_truncate_part3 truncate partition for (rank(1));
--
-- Insert few records into the table
--
insert into ck_sync1_ao_alter_part_truncate_part3 values ( generate_series(5,50),generate_series(15,60));
insert into ck_sync1_ao_alter_part_truncate_part3_A values ( generate_series(1,10),generate_series(21,30));
--
-- Alter the table set distributed by
--
Alter table ck_sync1_ao_alter_part_truncate_part3 set with ( reorganize='true') distributed by (unique2);
--
-- select from the Table
--
select count(*) from ck_sync1_ao_alter_part_truncate_part3;
--
-- Truncate default partition
--
alter table ck_sync1_ao_alter_part_truncate_part3 truncate default partition;
--
-- Insert few records into the table
--
insert into ck_sync1_ao_alter_part_truncate_part3 values ( generate_series(5,50),generate_series(15,60));
insert into ck_sync1_ao_alter_part_truncate_part3_A values ( generate_series(1,10),generate_series(21,30));
--
-- select from the Table
--
select count(*) from ck_sync1_ao_alter_part_truncate_part3;
--
-- ALTER CT AO
--
--
-- Truncate Partition
--
alter table ct_ao_alter_part_truncate_part1 truncate partition for (rank(1));
--
-- Insert few records into the table
--
insert into ct_ao_alter_part_truncate_part1 values ( generate_series(5,50),generate_series(15,60));
insert into ct_ao_alter_part_truncate_part1_A values ( generate_series(1,10),generate_series(21,30));
--
-- Alter the table set distributed by
--
Alter table ct_ao_alter_part_truncate_part1 set with ( reorganize='true') distributed by (unique2);
--
-- select from the Table
--
select count(*) from ct_ao_alter_part_truncate_part1;
--
-- Truncate default partition
--
alter table ct_ao_alter_part_truncate_part1 truncate default partition;
--
-- Insert few records into the table
--
insert into ct_ao_alter_part_truncate_part1 values ( generate_series(5,50),generate_series(15,60));
insert into ct_ao_alter_part_truncate_part1_A values ( generate_series(1,10),generate_series(21,30));
--
-- select from the Table
--
select count(*) from ct_ao_alter_part_truncate_part1;
| true |
cc516a6e478362cab8946286a16cb60d447dc5af | SQL | radtek/abs3 | /sql/mmfo/barsaq/Table/bankdates.sql | WINDOWS-1251 | 3,260 | 3.5625 | 4 | [] | no_license |
PROMPT =====================================================================================
PROMPT *** Run *** ========== Scripts /Sql/BARSAQ/Table/BANKDATES.sql =========*** Run *** =
PROMPT =====================================================================================
PROMPT *** Create table BANKDATES ***
begin
execute immediate '
CREATE TABLE BARSAQ.BANKDATES
( BANK_ID VARCHAR2(11),
BANKDATE DATE,
CONSTRAINT PK_BANKDATES PRIMARY KEY (BANK_ID) ENABLE
) ORGANIZATION INDEX NOCOMPRESS PCTFREE 10 INITRANS 2 MAXTRANS 255 LOGGING
TABLESPACE BRSSMLD
PCTTHRESHOLD 50ROWDEPENDENCIES ';
exception when others then
if sqlcode=-955 then null; else raise; end if;
end;
/
COMMENT ON TABLE BARSAQ.BANKDATES IS ' ()';
COMMENT ON COLUMN BARSAQ.BANKDATES.BANK_ID IS 'ID ';
COMMENT ON COLUMN BARSAQ.BANKDATES.BANKDATE IS ' ';
PROMPT *** Create constraint CC_BANKDATES_BANKID_NN ***
begin
execute immediate '
ALTER TABLE BARSAQ.BANKDATES MODIFY (BANK_ID CONSTRAINT CC_BANKDATES_BANKID_NN NOT NULL ENABLE)';
exception when others then
if sqlcode=-2260 or sqlcode=-2261 or sqlcode=-2264 or sqlcode=-2275 or sqlcode=-1442 then null; else raise; end if;
end;
/
PROMPT *** Create constraint CC_BANKDATES_BANKDATE_NN ***
begin
execute immediate '
ALTER TABLE BARSAQ.BANKDATES MODIFY (BANKDATE CONSTRAINT CC_BANKDATES_BANKDATE_NN NOT NULL ENABLE)';
exception when others then
if sqlcode=-2260 or sqlcode=-2261 or sqlcode=-2264 or sqlcode=-2275 or sqlcode=-1442 then null; else raise; end if;
end;
/
PROMPT *** Create constraint PK_BANKDATES ***
begin
execute immediate '
ALTER TABLE BARSAQ.BANKDATES ADD CONSTRAINT PK_BANKDATES PRIMARY KEY (BANK_ID)
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
TABLESPACE BRSSMLD ENABLE';
exception when others then
if sqlcode=-2260 or sqlcode=-2261 or sqlcode=-2264 or sqlcode=-2275 or sqlcode=-1442 then null; else raise; end if;
end;
/
PROMPT *** Create constraint CC_BANKDATES_BANKDATE_CC ***
begin
execute immediate '
ALTER TABLE BARSAQ.BANKDATES ADD CONSTRAINT CC_BANKDATES_BANKDATE_CC CHECK (trunc(bankdate)=bankdate) ENABLE';
exception when others then
if sqlcode=-2260 or sqlcode=-2261 or sqlcode=-2264 or sqlcode=-2275 or sqlcode=-1442 then null; else raise; end if;
end;
/
PROMPT *** Create index PK_BANKDATES ***
begin
execute immediate '
CREATE UNIQUE INDEX BARSAQ.PK_BANKDATES ON BARSAQ.BANKDATES (BANK_ID)
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
TABLESPACE BRSSMLD ';
exception when others then
if sqlcode=-955 then null; else raise; end if;
end;
/
PROMPT *** Create grants BANKDATES ***
grant SELECT on BANKDATES to BARSREADER_ROLE;
PROMPT =====================================================================================
PROMPT *** End *** ========== Scripts /Sql/BARSAQ/Table/BANKDATES.sql =========*** End *** =
PROMPT =====================================================================================
| true |
333c108d15c3b33d288e351a9b409b883291fb7c | SQL | huntdesignco/jade-cms-php | /database/pages.sql | UTF-8 | 359 | 2.6875 | 3 | [] | no_license | /*!40101 SET NAMES binary*/;
/*!40014 SET FOREIGN_KEY_CHECKS=0*/;
CREATE TABLE `pages` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`title` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`twig_template` text NOT NULL,
`is_navbar` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
| true |
3d1b653d90fcca42a65d6e75f596ecc574cc046c | SQL | murari-goswami/bi | /ETL/DataVirtuality/views/tableau/tableau.ops_address_change.sql | UTF-8 | 1,744 | 3.6875 | 4 | [] | no_license | -- Name: tableau.ops_address_change
-- Created: 2015-09-01 17:50:22
-- Updated: 2015-09-01 17:50:22
create view tableau.ops_address_change
as
with c_order as
(
SELECT
rank() OVER(PARTITION BY customer_id ORDER BY date_created asc) as rank_cust,
order_id,
order_type,
customer_id,
date_created,
kept_state,
payment_type,
date_invoiced,
shipping_city,
shipping_country,
shipping_street,
shipping_street_number,
shipping_zip,
shipping_first_name,
shipping_last_name,
shipping_co,
given_to_debt_collection,
case when revenue_state='Final' then sales_kept end as sales_kept,
case when revenue_state='Final' then articles_kept end as items_kept
from bi.customer_order
)
select
a.customer_id,
CASE
WHEN
a.shipping_first_name=b.shipping_first_name
AND a.shipping_last_name=b.shipping_last_name
AND a.shipping_street=b.shipping_street
AND a.shipping_street_number=b.shipping_street_number
AND a.shipping_zip=b.shipping_zip
AND a.shipping_city=b.shipping_city
AND a.shipping_co=b.shipping_co
THEN 'Y'
ELSE 'N'
end second_addres_change
from
(
select
co.customer_id,
co.shipping_city,
co.shipping_country,
co.shipping_street,
co.shipping_street_number,
co.shipping_zip,
co.shipping_first_name,
co.shipping_last_name,
co.shipping_co
from c_order co
where rank_cust=1
)a
left join
(
select
customer_id,
co.shipping_city,
co.shipping_country,
co.shipping_street,
co.shipping_street_number,
co.shipping_zip,
co.shipping_first_name,
co.shipping_last_name,
co.shipping_co
from c_order co
where rank_cust=2
)b on a.customer_id=b.customer_id
| true |
e72f88b702106f83739de3ea51467d649f4d937c | SQL | SdMSyN/eva_ins | /db_schemas/eva_ins_escuelas_secretarias.sql | UTF-8 | 1,695 | 2.90625 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.3.11
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 07-11-2016 a las 02:10:09
-- Versión del servidor: 5.6.24
-- Versión de PHP: 5.5.24
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de datos: `eva_ins`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios_escuelas_secretarias`
--
CREATE TABLE IF NOT EXISTS `usuarios_escuelas_secretarias` (
`id` int(11) NOT NULL,
`nombre` varchar(100) NOT NULL,
`user` varchar(20) NOT NULL,
`pass` varchar(20) NOT NULL,
`clave` varchar(20) NOT NULL,
`informacion_id` int(11) NOT NULL,
`escuela_id` int(11) NOT NULL,
`creado` date NOT NULL,
`actualizado` date NOT NULL,
`activo` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `usuarios_escuelas_secretarias`
--
ALTER TABLE `usuarios_escuelas_secretarias`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `usuarios_escuelas_secretarias`
--
ALTER TABLE `usuarios_escuelas_secretarias`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
dbdfbdec163285593930e0bcfef214442f587a73 | SQL | True-Evzheniy/92049-yeticave-10 | /queries.sql | UTF-8 | 3,598 | 3.234375 | 3 | [] | no_license | # Fill categories
INSERT INTO categories
SET name = 'Доски и лыжи',
symbol_code ='boards';
INSERT INTO categories
SET name = 'Крепления',
symbol_code = 'attachment';
INSERT INTO categories
SET name = 'Ботинки',
symbol_code = 'boots';
INSERT INTO categories
SET name = 'Одежда',
symbol_code = 'clothing';
INSERT INTO categories
SET name = 'Инструменты',
symbol_code = 'tools';
INSERT INTO categories
SET name = 'Разное',
symbol_code = 'other';
# Fill a few users
INSERT INTO users
SET email ='vasyafrommoscow@yandex.ru',
name = 'Вася',
password = 'qwerty',
contacts = 'Москва';
INSERT INTO users
SET email ='petya@mail.ru',
name = 'Петя',
password = 'strong9password',
contacts = 'Воркута';
INSERT INTO users
SET email ='maria@gmail.com',
name = 'Маша',
password = 'mybirthday2',
contacts = 'Новосибирск';
# Fill lots
INSERT INTO lots
SET name = '2014 Rossignol District Snowboard',
start_price = 10999,
picture = 'img/lot-1.jpg',
expiry_date = STR_TO_DATE('2019-09-01', '%Y-%m-%d'),
description = 'asdfsdf',
user_id = 1,
category_id = 1,
bet_step = 1;
INSERT INTO lots
SET name = 'DC Ply Mens 2016/2017 Snowboard',
start_price = 159999,
picture = 'img/lot-2.jpg',
expiry_date = STR_TO_DATE('2019-09-05', '%Y-%m-%d'),
description = 'Lorem i t.d.',
user_id = 2,
category_id = 1,
bet_step = 2;
INSERT INTO lots
SET name = 'Крепления Union Contact Pro 2015 года размер L/XL',
start_price = 159999,
picture = 'img/lot-3.jpg',
expiry_date = STR_TO_DATE('2019-09-04', '%Y-%m-%d'),
description = 'Ipsum and more words',
user_id = 1,
category_id = 1,
bet_step = 2;
INSERT INTO lots
SET name = 'Ботинки для сноуборда DC Mutiny Charocal',
start_price = 159999,
picture = 'img/lot-4.jpg',
expiry_date = STR_TO_DATE('2019-09-04', '%Y-%m-%d'),
description = 'Ipsum and more words',
user_id = 2,
category_id = 3,
bet_step = 3;
INSERT INTO lots
SET name = 'Куртка для сноуборда DC Mutiny Charocal',
start_price = 7500,
picture = 'img/lot-5.jpg',
expiry_date = STR_TO_DATE('2019-09-02', '%Y-%m-%d'),
description = 'Ipsum and more words',
user_id = 2,
category_id = 4,
bet_step = 4;
INSERT INTO lots
SET name = 'Маска Oakley Canopy',
start_price = 5400,
picture = 'img/lot-6.jpg',
expiry_date = STR_TO_DATE('2019-09-03', '%Y-%m-%d'),
description = 'Ipsum and more words',
user_id = 3,
category_id = 6,
bet_step = 3;
# Fill bets
INSERT INTO bets
SET amount = 5430,
lot_id = 6,
user_id = 1;
INSERT INTO bets
SET amount = 12000,
lot_id = 1,
user_id = 2;
INSERT INTO bets
SET amount = 170000,
lot_id = 2,
user_id = 3;
# Get all categories
SELECT *
from categories;
# Get open lots
SELECT name, start_price, picture, amount, category_id
FROM lots
LEFT JOIN bets ON lots.id = bets.lot_id
WHERE expiry_date > NOW();
# Get lot with category name by id
SELECT lots.name, start_price, expiry_date, picture, categories.name as category_name
FROM lots
LEFT JOIN categories ON lots.category_id = categories.id
WHERE lots.id = 2;
# Update lot name
UPDATE lots
SET name = 'new lot name'
WHERE id = 1;
# Get bets for lot sorted by date
SELECT *
FROM bets
WHERE lot_id = 2
ORDER BY date DESC;
| true |
826f9d4b971d4e2d1372496856ff96c7fd54f9f3 | SQL | nooblenabot/PhoneBack | /install/sql/appels.sql | ISO-8859-1 | 8,487 | 3.484375 | 3 | [] | no_license | # phpMyAdmin SQL Dump
# version 2.5.3
# http://www.phpmyadmin.net
#
# Serveur: localhost
# Gnr le : Mardi 06 Juin 2006 16:48
# Version du serveur: 4.0.15
# Version de PHP: 4.3.3
#
# Base de donnes: `appels`
#
# --------------------------------------------------------
#
# Structure de la table `appel`
#
# Cration: Lundi 29 Mai 2006 12:32
# Dernire modification: Jeudi 01 Juin 2006 15:55
#
CREATE TABLE `appel` (
`id` int(10) NOT NULL auto_increment,
`date_appel` datetime NOT NULL default '0000-00-00 00:00:00',
`envoimail` varchar(5) default NULL,
`commentaire` text,
`tel` varchar(14) default NULL,
`id_humeur` int(10) NOT NULL default '0',
`id_lieu` int(10) default NULL,
`id_structure` int(10) NOT NULL default '0',
`id_issue` int(10) NOT NULL default '0',
`id_destinataire` int(10) NOT NULL default '0',
`id_type` int(10) NOT NULL default '0',
`id_utilisateur` int(10) NOT NULL default '0',
`id_personne` int(10) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8394 ;
#
# Contenu de la table `appel`
#
# --------------------------------------------------------
#
# Structure de la table `destination_appel_def`
#
# Cration: Lundi 29 Mai 2006 12:32
# Dernire modification: Mardi 06 Juin 2006 12:08
#
CREATE TABLE `destination_appel_def` (
`id_destinataire` int(10) NOT NULL default '0',
`id_type` int(10) NOT NULL default '0'
) ENGINE=MyISAM;
#
# Contenu de la table `destination_appel_def`
#
INSERT INTO `destination_appel_def` (`id_destinataire`, `id_type`) VALUES (285, 1),
(284, 26),
(284, 32),
(1, 4),
(286, 5);
# --------------------------------------------------------
#
# Structure de la table `droits_acces`
#
# Cration: Mardi 30 Mai 2006 14:46
# Dernire modification: Jeudi 01 Juin 2006 16:01
#
CREATE TABLE `droits_acces` (
`id` int(11) NOT NULL auto_increment,
`idrubrique` int(11) NOT NULL default '0',
`idutilisateur` int(11) NOT NULL default '0',
`acces` char(3) NOT NULL default 'oui',
PRIMARY KEY (`id`)
) ENGINE=MyISAM COMMENT='Gestion d''un droit d''accs (oui ou non) par rubrique et par ' AUTO_INCREMENT=49 ;
#
# Contenu de la table `droits_acces`
#
INSERT INTO `droits_acces` (`id`, `idrubrique`, `idutilisateur`, `acces`) VALUES (21, 1, 6, 'oui'),
(22, 2, 6, 'oui'),
(23, 3, 6, 'oui'),
(24, 4, 6, 'oui');
# --------------------------------------------------------
#
# Structure de la table `humeur`
#
# Cration: Lundi 29 Mai 2006 12:32
# Dernire modification: Lundi 29 Mai 2006 12:33
#
CREATE TABLE `humeur` (
`id` int(10) NOT NULL auto_increment,
`libelle` varchar(20) NOT NULL default '',
`description` varchar(30) default NULL,
`smiley` varchar(50) NOT NULL default '',
`defaut` char(3) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 ;
#
# Contenu de la table `humeur`
#
INSERT INTO `humeur` (`id`, `libelle`, `description`, `smiley`, `defaut`) VALUES (1, 'Mauvaise', NULL, 'images/icon_mauvaise.gif', NULL),
(2, 'Moyenne', NULL, 'images/icon_moyenne.gif', NULL),
(3, 'Normale', NULL, 'images/icon_normale.gif', NULL),
(4, 'Bonne', NULL, 'images/icon_bonne.gif', NULL),
(5, 'Excellente', NULL, 'images/icon_excellente.gif', NULL),
(6, 'Ne se prononce pas', NULL, 'images/icon_question.gif', 'oui');
# --------------------------------------------------------
#
# Structure de la table `issue`
#
# Cration: Lundi 29 Mai 2006 12:32
# Dernire modification: Mardi 06 Juin 2006 16:35
#
CREATE TABLE `issue` (
`id` int(10) NOT NULL auto_increment,
`libelle` varchar(30) NOT NULL default '',
`description` varchar(30) default NULL,
`defaut` char(3) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=20 ;
#
# Contenu de la table `issue`
#
INSERT INTO `issue` (`id`, `libelle`, `description`, `defaut`) VALUES (1, 'Appel pris', '', 'oui'),
(2, 'Il rappellera', NULL, 'non'),
(3, 'Le rappeler', NULL, 'non'),
(4, 'Autre', NULL, 'non'),
(5, 'Il tlphone sur portable', NULL, 'non'),
(6, 'Il envoie un mail', NULL, 'non');
# --------------------------------------------------------
#
# Structure de la table `lieu`
#
# Cration: Mardi 06 Juin 2006 15:35
# Dernire modification: Mardi 06 Juin 2006 15:35
#
CREATE TABLE `lieu` (
`id` int(10) NOT NULL auto_increment,
`nom` varchar(50) NOT NULL default '',
`codepostal` int(5) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 ;
#
# Contenu de la table `lieu`
#
# --------------------------------------------------------
#
# Structure de la table `personne`
#
# Cration: Mardi 06 Juin 2006 15:33
# Dernire modification: Mardi 06 Juin 2006 15:33
#
CREATE TABLE `personne` (
`id` int(10) NOT NULL auto_increment,
`nom` varchar(50) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 ;
#
# Contenu de la table `personne`
#
# --------------------------------------------------------
#
# Structure de la table `rubrique`
#
# Cration: Mardi 30 Mai 2006 14:49
# Dernire modification: Mardi 30 Mai 2006 14:51
#
CREATE TABLE `rubrique` (
`id` int(11) NOT NULL auto_increment,
`lib` varchar(255) NOT NULL default '',
`ordre_affichage` int(11) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 ;
#
# Contenu de la table `rubrique`
#
INSERT INTO `rubrique` (`id`, `lib`, `ordre_affichage`) VALUES (1, 'SAISIE', 1),
(2, 'CONSULTATION', 2),
(3, 'STATISTIQUES', 3),
(4, 'ADMINISTRATION', 4);
# --------------------------------------------------------
#
# Structure de la table `structure`
#
# Cration: Lundi 29 Mai 2006 14:56
# Dernire modification: Mardi 06 Juin 2006 12:21
#
CREATE TABLE `structure` (
`id` int(10) NOT NULL auto_increment,
`nom` varchar(50) NOT NULL default '',
`defaut` char(3) default 'Non',
`Client` char(3) default 'Oui',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=46 ;
#
# Contenu de la table `structure`
#
INSERT INTO `structure` (`id`, `nom`, `defaut`, `client`) VALUES (17, 'Collge', 'non', 'oui'),
(45, 'Service interne', 'oui', 'oui'),
(20, 'Autre', 'non', 'oui'),
(11, 'Particulier', 'non', 'oui');
# --------------------------------------------------------
#
# Structure de la table `destinataire`
#
# Cration: Mardi 06 Juin 2006 10:51
# Dernire modification: Mardi 06 Juin 2006 12:07
#
CREATE TABLE `destinataire` (
`id` int(10) NOT NULL auto_increment,
`nom` varchar(30) NOT NULL default '',
`prenom` varchar(30) NOT NULL default '',
`mail` varchar(50) NOT NULL default '',
`tel` varchar(14) default NULL,
`id_structure` int(10) NOT NULL,
`defaut` char(3) default 'non',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=287 ;
#
# Contenu de la table `destinataire`
#
INSERT INTO `destinataire` (`id`, `nom`, `prenom`, `mail`, `tel`,`id_structure`, `defaut`) VALUES (284, 'Durand', 'Robert', 'rdurand@mondomaine.com', 'Poste 327',17, 'non'),
(285, 'Dufour', 'Josiane', 'jdufour@mondomaine.com', '7997',11, 'non'),
(286, 'Duchmol', 'Jean Jacques', 'jduch@mondomaine.com', '35-55',20, 'oui');
# --------------------------------------------------------
#
# Structure de la table `type`
#
# Cration: Lundi 29 Mai 2006 12:33
# Dernire modification: Mardi 06 Juin 2006 16:21
#
CREATE TABLE `type` (
`id` int(10) NOT NULL auto_increment,
`libelle` varchar(30) NOT NULL default '',
`description` varchar(30) default NULL,
`defaut` char(3) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=35 ;
#
# Contenu de la table `type`
#
INSERT INTO `type` (`id`, `libelle`, `description`, `defaut`) VALUES (1, 'Support', '', 'oui'),
(5, 'Comptabilit', '', 'non'),
(26, 'Autre', '', 'non'),
(34, 'Dmarche commerciale', '', 'non');
# --------------------------------------------------------
#
# Structure de la table `utilisateur`
#
# Cration: Lundi 29 Mai 2006 12:33
# Dernire modification: Jeudi 01 Juin 2006 16:01
#
CREATE TABLE `utilisateur` (
`id` int(10) NOT NULL auto_increment,
`nom` varchar(30) NOT NULL default '',
`prenom` varchar(30) NOT NULL default '',
`login` varchar(20) NOT NULL default '',
`motpasse` varchar(10) NOT NULL default '',
`mail` varchar(50) NOT NULL default '',
`Profil` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=24 ;
#
# Contenu de la table `utilisateur`
#
INSERT INTO `utilisateur` (`id`, `nom`, `prenom`, `login`, `motpasse`, `mail`,`Profil`) VALUES (6, 'ADMINISTRATEUR', 'admin', 'admin', 'password', 'info@erasme.org','1');
| true |
a477a11e504ac2f92197bedea385f0f9793e761f | SQL | preet-kaur/team-7 | /assets/backend/application.sql | UTF-8 | 2,057 | 3.265625 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Jul 21, 2018 at 04:36 AM
-- Server version: 10.1.28-MariaDB
-- PHP Version: 7.1.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `educon`
--
-- --------------------------------------------------------
--
-- Table structure for table `application`
--
CREATE TABLE `application` (
`aid` int(20) NOT NULL,
`id` int(20) NOT NULL,
`Status` varchar(20) NOT NULL,
`institute` varchar(50) NOT NULL,
`typeedu` varchar(50) NOT NULL,
`result` float NOT NULL,
`income` float NOT NULL,
`year` int(11) NOT NULL,
`occupation` varchar(50) NOT NULL,
`did` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `application`
--
INSERT INTO `application` (`aid`, `id`, `Status`, `institute`, `typeedu`, `result`, `income`, `year`, `occupation`, `did`) VALUES
(1, 1, '1', 'Ruia', '12th', 89, 10000, 2014, 'Farmer', 1),
(3, 1, '1', 'Ruia', '11th', 80, 12000, 2013, 'Farmer', 2),
(4, 408, '1', 'DJ Sanghvi', 'Medical', 55, 10000, 2017, 'Farmer', 395),
(5, 393, '2', 'SPIT', 'Engineering', 70, 15000, 2017, 'Worker', 395);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `application`
--
ALTER TABLE `application`
ADD PRIMARY KEY (`aid`),
ADD UNIQUE KEY `id` (`aid`),
ADD UNIQUE KEY `Did` (`aid`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `application`
--
ALTER TABLE `application`
MODIFY `aid` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
8784b624afbd05232deb4a8d3aa015c96f204f7f | SQL | avetall87/otus_spring_2019_11 | /hw6-library-app/src/main/resources/db/migration/V1.0.0__base_schema_structure.sql | UTF-8 | 1,556 | 4 | 4 | [] | no_license | create table authors
(
id long auto_increment
constraint author_pk PRIMARY KEY,
first_name varchar2(250) not null,
last_name varchar2(250) not null,
patronymic varchar2(250) not null
);
create table books
(
id long auto_increment
constraint book_pk PRIMARY KEY,
name varchar2(1024) not null,
description varchar2(4000 char)
);
create table authors_books
(
id long auto_increment
constraint author_book_pk PRIMARY KEY,
author_id long not null references authors (id) ON DELETE CASCADE,
book_id long not null references books (id) ON DELETE CASCADE
);
create index authors_books_author_id_idx ON authors_books (author_id);
create index authors_books_book_id_idx ON authors_books (book_id);
create table genres
(
id long auto_increment
constraint genre_pk PRIMARY KEY,
name varchar2(1024) not null
);
create table books_genres
(
id long auto_increment
constraint book_genre_pk PRIMARY KEY,
book_id long not null references books (id) ON DELETE CASCADE,
genre_id long not null references genres (id) ON DELETE CASCADE
);
create index books_genres_book_id ON books_genres (book_id);
create index books_genres_genre_id ON books_genres (genre_id);
create table comments
(
id long auto_increment
constraint comment_pk PRIMARY KEY,
book_id long not null references books (id) on delete cascade,
comment varchar2(4000) not null
);
create index comments_idx ON comments (book_id); | true |
d96b00079d59d1e170288bb4ced44c7ea4451428 | SQL | TrinityChristiana/chinook-trinityterry | /queries/finished/top_country.sql | UTF-8 | 178 | 3.453125 | 3 | [] | no_license | -- Which country's customers spent the most?
SELECT
i.BillingCountry 'Country',
SUM(i.Total) Sales
FROM Invoice i
GROUP BY i.BillingCountry
ORDER BY Sales DESC
LIMIT 1; | true |
3bd69a6092b758b10a2f098d9c71e6f5bfb73f05 | SQL | EddyeBoy27/one-for-all | /desafios/desafio1.sql | UTF-8 | 3,907 | 4 | 4 | [] | no_license | CREATE DATABASE IF NOT EXISTS SpotifyClone;
USE SpotifyClone;
CREATE TABLE users(
id INT PRIMARY KEY auto_increment,
user_name VARCHAR(50) NOT NULL,
user_age INT NOT NULL
) engine = InnoDB AUTO_INCREMENT = 15;
CREATE TABLE plans(
id INT PRIMARY KEY auto_increment,
plan_name VARCHAR(50) NOT NULL,
price DECIMAL(5, 2) NOT NULL
) engine = InnoDB;
CREATE TABLE artists(
id INT PRIMARY KEY auto_increment,
artist_name VARCHAR(50) NOT NULL
) engine = InnoDB;
CREATE TABLE plans_purchases(
user_id INT NOT NULL,
plan_id INT NOT NULL,
PRIMARY KEY(user_id, plan_id),
FOREIGN KEY(user_id) references users(id),
FOREIGN KEY(plan_id) references plans(id)
) engine = InnoDB;
CREATE TABLE albuns(
id INT PRIMARY KEY auto_increment,
album_name VARCHAR(80) NOT NULL
) engine = InnoDB;
CREATE TABLE songs(
id INT PRIMARY KEY auto_increment,
song_name VARCHAR(150) NOT NULL
) engine = InnoDB;
CREATE TABLE albuns_songs(
album_id INT NOT NULL,
song_id INT NOT NULL,
PRIMARY KEY(album_id, song_id),
FOREIGN KEY(album_id) references albuns(id),
FOREIGN KEY(song_id) references songs(id)
) engine = InnoDB;
CREATE TABLE album_artists(
artist_id INT NOT NULL,
album_id INT NOT NULL,
PRIMARY KEY(artist_id, album_id),
FOREIGN KEY(artist_id) references artists(id),
FOREIGN KEY(album_id) references albuns(id)
) engine = InnoDB;
CREATE TABLE history(
user_id INT NOT NULL,
song_id INT NOT NULL,
PRIMARY KEY(user_id, song_id),
FOREIGN KEY(user_id) references users(id),
FOREIGN KEY(song_id) references songs(id)
) engine = InnoDB;
CREATE TABLE followers(
user_id INT NOT NULL,
artist_id INT NOT NULL,
PRIMARY KEY(user_id, artist_id),
FOREIGN KEY(user_id) references users(id),
FOREIGN KEY(artist_id) references artists(id)
) engine = InnoDB;
DELIMITER $$
CREATE TRIGGER trigger_usuario_delete
BEFORE DELETE ON users
FOR EACH ROW
BEGIN
DELETE FROM plans_purchases
WHERE user_id = OLD.id;
DELETE FROM history
WHERE user_id = OLD.id;
DELETE FROM followers
WHERE user_id = OLD.id;
END $$
DELIMITER ;
INSERT INTO
users (user_name, user_age)
VALUES
("Thati", 23),
("Cintia", 35),
("Bill", 20),
("Roger", 45);
INSERT INTO
plans (plan_name, price)
VALUES
("Gratuito", 0),
("Familiar", 7.99),
("Universitário", 5.99);
INSERT INTO
artists (artist_name)
VALUES
("Walter Phoenix"),
("Peter Strong"),
("Lance Day"),
("Freedie Shannon");
INSERT INTO
plans_purchases (user_id, plan_id)
VALUES
(15, 1),
(16, 2),
(17, 3),
(18, 1);
INSERT INTO
albuns (id, album_name)
VALUES
(1, 'Envious'),
(2, 'Exuberant'),
(3, 'Hallowed Steam'),
(4, 'Incandescent'),
(5, 'Temporary Culture');
INSERT INTO
songs (id, song_name)
VALUES
(1, 'Soul For Us'),
(2, 'Reflections Of Magic'),
(3, 'Dance With Her Own'),
(4, 'Troubles Of My Inner Fire'),
(5, 'Time Fireworks'),
(6, 'Magic Circus'),
(7, 'Honey, So Do I'),
(8, 'Sweetie, Let\'s Go Wild'),
(9, 'She Knows'),
(10, 'Fantasy For Me'),
(11, 'Celebration Of More'),
(12, 'Rock His Everything'),
(13, 'Home Forever'),
(14, 'Diamond Power'),
(15, 'Honey, Let\'s Be Silly'),
(16, 'Thang Of Thunder'),
(17, 'Words Of Her Life'),
(18, 'Without My Streets');
INSERT INTO
albuns_songs (album_id, song_id)
VALUES
(1, 1),
(1, 2),
(1, 3),
(2, 4),
(2, 5),
(3, 6),
(3, 7),
(3, 8),
(3, 9),
(4, 10),
(4, 11),
(4, 12),
(4, 13),
(4, 14),
(4, 15),
(5, 16),
(5, 17),
(5, 18);
INSERT INTO
album_artists (artist_id, album_id)
VALUES
(1, 1),
(1, 2),
(2, 3),
(3, 4),
(4, 5);
INSERT INTO
history (user_id, song_id)
VALUES
(15,1),
(15,6),
(15,14),
(15,16),
(16,13),
(16,17),
(16,2),
(16,15),
(17,4),
(17,16),
(17,6),
(18,3),
(18,18),
(18,11);
INSERT INTO
followers (user_id, artist_id)
VALUES
(15, 1),
(15, 4),
(15, 3),
(16, 1),
(16, 3),
(17, 2),
(17, 1),
(18, 4);
| true |
19c418dc0def41952245243ec797e870b45f0ac7 | SQL | valergrad/oraclescripts | /ParallelSkewAtPlan.sql | UTF-8 | 826 | 3.390625 | 3 | [] | no_license | -- parallellism & plan
select session_id,
px,
listagg( case when sql_plan_line_id is null then 'null' else to_char(sql_plan_line_id) end || '(' || cnt || ')' || ' ') within group ( order by cnt desc) plan_lines,
sum(cnt) cnt
from ( select session_id,
sql_plan_line_id,
sql_plan_operation,
program,
case when program like 'oracle@' || host_name || '%' then '~' || substr( program, 10 + length(host_name), 4) else program end px,
count (*) cnt
from dba_hist_active_sess_history ash, v$instance inst
where ash.sql_id = :sql_id and sql_exec_id = (16777215 + :exec_id)
group by session_id,
sql_plan_line_id,
sql_plan_operation,
program,
inst.host_name
)
group by session_id, px
order by px; | true |
f641d10f813f6b0508fbdf65ffe336cd3cedbdf2 | SQL | C-Laborde/sql-course | /Ex4 - JOINS.sql | UTF-8 | 1,289 | 4.375 | 4 | [] | no_license | -- JOIN order_items with products
USE sql_store;
SELECT order_id, oi.product_id, quantity, oi.unit_price
FROM order_items oi
JOIN products p
ON oi.product_id = p.product_id;
-- JOIN MULTIPLE tables
USE sql_invoicing;
SELECT
p.date,
p.invoice_id,
p.amount,
c.name,
pm.name AS payment_method
FROM payments p
JOIN payment_methods pm
ON p.payment_method = pm.payment_method_id
JOIN clients c
ON p.client_id = c.client_id;
-- OUTER JOIN
USE sql_store;
SELECT
p.product_id,
p.name,
oi.quantity
FROM products p
LEFT JOIN order_items oi
ON p.product_id = oi.product_id;
SELECT
o.order_date,
o.order_id,
c.first_name AS customer,
s.name AS shipper,
os.name as status
FROM orders o
JOIN customers c
ON o.customer_id = c.customer_id
LEFT JOIN shippers s
ON o.shipper_id = s.shipper_id
JOIN order_statuses os
ON o.status = os.order_status_id
ORDER BY o.status;
-- USING clause
USE sql_invoicing;
SELECT
p.date,
c.name AS client,
p.amount,
pm.name
FROM payments p
JOIN clients c
USING (client_id)
JOIN payment_methods pm
ON p.payment_method = pm.payment_method_id;
-- CROSS JOINS
USE sql_store;
SELECT *
-- implicit syntax
-- FROM shippers s, products p
-- explicit syntax
FROM shippers s
CROSS JOIN products p
ORDER BY s.name
| true |
b2e5473f13c7dea58d55fa8dbcc714aca0cc67b5 | SQL | elguille86/mvcphp | /DESARROLLO/mvcphp.sql | ISO-8859-1 | 18,659 | 2.859375 | 3 | [] | no_license | # MySQL-Front 5.1 (Build 3.18)
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE */;
/*!40101 SET SQL_MODE='' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES */;
/*!40103 SET SQL_NOTES='ON' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;
# Host: localhost Database: mvcphp
# ------------------------------------------------------
# Server version 5.5.8-log
DROP DATABASE IF EXISTS `mvcphp`;
CREATE DATABASE `mvcphp` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `mvcphp`;
#
# Source for table posts
#
DROP TABLE IF EXISTS `posts`;
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`titulo` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
`cuerpo` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
#
# Dumping data for table posts
#
LOCK TABLES `posts` WRITE;
/*!40000 ALTER TABLE `posts` DISABLE KEYS */;
INSERT INTO `posts` VALUES (2,'post2','Mensaje de prueba actualizado.');
INSERT INTO `posts` VALUES (5,'Diseo','Es una una pagina chevere , esta de prueba .');
INSERT INTO `posts` VALUES (6,'"Nio"','<script>alert('Hola Mundo');</script>');
INSERT INTO `posts` VALUES (7,'Usuario Administrador','Registro con datos de usuario autenticado.');
INSERT INTO `posts` VALUES (8,'Mensaje ','Desde la pc de mi trabajo');
INSERT INTO `posts` VALUES (9,'sugerencia','contenido de mensaje');
INSERT INTO `posts` VALUES (10,'Guillermo','Es una prueba hecha a las 5:31 7-4-2014');
INSERT INTO `posts` VALUES (11,'Guillermo','Prueba 5:32pm');
INSERT INTO `posts` VALUES (12,'demo','Es un buen ejemplo ');
INSERT INTO `posts` VALUES (13,'Demo','Todo es posible con la Tecnologia....');
INSERT INTO `posts` VALUES (14,'Guillermo','Una de las mejores pelculas es la IRON MAN 2 y El Sorprendente Hombre Araa');
/*!40000 ALTER TABLE `posts` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table prueba
#
DROP TABLE IF EXISTS `prueba`;
CREATE TABLE `prueba` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=301 DEFAULT CHARSET=utf8;
#
# Dumping data for table prueba
#
LOCK TABLES `prueba` WRITE;
/*!40000 ALTER TABLE `prueba` DISABLE KEYS */;
INSERT INTO `prueba` VALUES (1,'nombre 0');
INSERT INTO `prueba` VALUES (2,'nombre 1');
INSERT INTO `prueba` VALUES (3,'nombre 2');
INSERT INTO `prueba` VALUES (4,'nombre 3');
INSERT INTO `prueba` VALUES (5,'nombre 4');
INSERT INTO `prueba` VALUES (6,'nombre 5');
INSERT INTO `prueba` VALUES (7,'nombre 6');
INSERT INTO `prueba` VALUES (8,'nombre 7');
INSERT INTO `prueba` VALUES (9,'nombre 8');
INSERT INTO `prueba` VALUES (10,'nombre 9');
INSERT INTO `prueba` VALUES (11,'nombre 10');
INSERT INTO `prueba` VALUES (12,'nombre 11');
INSERT INTO `prueba` VALUES (13,'nombre 12');
INSERT INTO `prueba` VALUES (14,'nombre 13');
INSERT INTO `prueba` VALUES (15,'nombre 14');
INSERT INTO `prueba` VALUES (16,'nombre 15');
INSERT INTO `prueba` VALUES (17,'nombre 16');
INSERT INTO `prueba` VALUES (18,'nombre 17');
INSERT INTO `prueba` VALUES (19,'nombre 18');
INSERT INTO `prueba` VALUES (20,'nombre 19');
INSERT INTO `prueba` VALUES (21,'nombre 20');
INSERT INTO `prueba` VALUES (22,'nombre 21');
INSERT INTO `prueba` VALUES (23,'nombre 22');
INSERT INTO `prueba` VALUES (24,'nombre 23');
INSERT INTO `prueba` VALUES (25,'nombre 24');
INSERT INTO `prueba` VALUES (26,'nombre 25');
INSERT INTO `prueba` VALUES (27,'nombre 26');
INSERT INTO `prueba` VALUES (28,'nombre 27');
INSERT INTO `prueba` VALUES (29,'nombre 28');
INSERT INTO `prueba` VALUES (30,'nombre 29');
INSERT INTO `prueba` VALUES (31,'nombre 30');
INSERT INTO `prueba` VALUES (32,'nombre 31');
INSERT INTO `prueba` VALUES (33,'nombre 32');
INSERT INTO `prueba` VALUES (34,'nombre 33');
INSERT INTO `prueba` VALUES (35,'nombre 34');
INSERT INTO `prueba` VALUES (36,'nombre 35');
INSERT INTO `prueba` VALUES (37,'nombre 36');
INSERT INTO `prueba` VALUES (38,'nombre 37');
INSERT INTO `prueba` VALUES (39,'nombre 38');
INSERT INTO `prueba` VALUES (40,'nombre 39');
INSERT INTO `prueba` VALUES (41,'nombre 40');
INSERT INTO `prueba` VALUES (42,'nombre 41');
INSERT INTO `prueba` VALUES (43,'nombre 42');
INSERT INTO `prueba` VALUES (44,'nombre 43');
INSERT INTO `prueba` VALUES (45,'nombre 44');
INSERT INTO `prueba` VALUES (46,'nombre 45');
INSERT INTO `prueba` VALUES (47,'nombre 46');
INSERT INTO `prueba` VALUES (48,'nombre 47');
INSERT INTO `prueba` VALUES (49,'nombre 48');
INSERT INTO `prueba` VALUES (50,'nombre 49');
INSERT INTO `prueba` VALUES (51,'nombre 50');
INSERT INTO `prueba` VALUES (52,'nombre 51');
INSERT INTO `prueba` VALUES (53,'nombre 52');
INSERT INTO `prueba` VALUES (54,'nombre 53');
INSERT INTO `prueba` VALUES (55,'nombre 54');
INSERT INTO `prueba` VALUES (56,'nombre 55');
INSERT INTO `prueba` VALUES (57,'nombre 56');
INSERT INTO `prueba` VALUES (58,'nombre 57');
INSERT INTO `prueba` VALUES (59,'nombre 58');
INSERT INTO `prueba` VALUES (60,'nombre 59');
INSERT INTO `prueba` VALUES (61,'nombre 60');
INSERT INTO `prueba` VALUES (62,'nombre 61');
INSERT INTO `prueba` VALUES (63,'nombre 62');
INSERT INTO `prueba` VALUES (64,'nombre 63');
INSERT INTO `prueba` VALUES (65,'nombre 64');
INSERT INTO `prueba` VALUES (66,'nombre 65');
INSERT INTO `prueba` VALUES (67,'nombre 66');
INSERT INTO `prueba` VALUES (68,'nombre 67');
INSERT INTO `prueba` VALUES (69,'nombre 68');
INSERT INTO `prueba` VALUES (70,'nombre 69');
INSERT INTO `prueba` VALUES (71,'nombre 70');
INSERT INTO `prueba` VALUES (72,'nombre 71');
INSERT INTO `prueba` VALUES (73,'nombre 72');
INSERT INTO `prueba` VALUES (74,'nombre 73');
INSERT INTO `prueba` VALUES (75,'nombre 74');
INSERT INTO `prueba` VALUES (76,'nombre 75');
INSERT INTO `prueba` VALUES (77,'nombre 76');
INSERT INTO `prueba` VALUES (78,'nombre 77');
INSERT INTO `prueba` VALUES (79,'nombre 78');
INSERT INTO `prueba` VALUES (80,'nombre 79');
INSERT INTO `prueba` VALUES (81,'nombre 80');
INSERT INTO `prueba` VALUES (82,'nombre 81');
INSERT INTO `prueba` VALUES (83,'nombre 82');
INSERT INTO `prueba` VALUES (84,'nombre 83');
INSERT INTO `prueba` VALUES (85,'nombre 84');
INSERT INTO `prueba` VALUES (86,'nombre 85');
INSERT INTO `prueba` VALUES (87,'nombre 86');
INSERT INTO `prueba` VALUES (88,'nombre 87');
INSERT INTO `prueba` VALUES (89,'nombre 88');
INSERT INTO `prueba` VALUES (90,'nombre 89');
INSERT INTO `prueba` VALUES (91,'nombre 90');
INSERT INTO `prueba` VALUES (92,'nombre 91');
INSERT INTO `prueba` VALUES (93,'nombre 92');
INSERT INTO `prueba` VALUES (94,'nombre 93');
INSERT INTO `prueba` VALUES (95,'nombre 94');
INSERT INTO `prueba` VALUES (96,'nombre 95');
INSERT INTO `prueba` VALUES (97,'nombre 96');
INSERT INTO `prueba` VALUES (98,'nombre 97');
INSERT INTO `prueba` VALUES (99,'nombre 98');
INSERT INTO `prueba` VALUES (100,'nombre 99');
INSERT INTO `prueba` VALUES (101,'nombre 100');
INSERT INTO `prueba` VALUES (102,'nombre 101');
INSERT INTO `prueba` VALUES (103,'nombre 102');
INSERT INTO `prueba` VALUES (104,'nombre 103');
INSERT INTO `prueba` VALUES (105,'nombre 104');
INSERT INTO `prueba` VALUES (106,'nombre 105');
INSERT INTO `prueba` VALUES (107,'nombre 106');
INSERT INTO `prueba` VALUES (108,'nombre 107');
INSERT INTO `prueba` VALUES (109,'nombre 108');
INSERT INTO `prueba` VALUES (110,'nombre 109');
INSERT INTO `prueba` VALUES (111,'nombre 110');
INSERT INTO `prueba` VALUES (112,'nombre 111');
INSERT INTO `prueba` VALUES (113,'nombre 112');
INSERT INTO `prueba` VALUES (114,'nombre 113');
INSERT INTO `prueba` VALUES (115,'nombre 114');
INSERT INTO `prueba` VALUES (116,'nombre 115');
INSERT INTO `prueba` VALUES (117,'nombre 116');
INSERT INTO `prueba` VALUES (118,'nombre 117');
INSERT INTO `prueba` VALUES (119,'nombre 118');
INSERT INTO `prueba` VALUES (120,'nombre 119');
INSERT INTO `prueba` VALUES (121,'nombre 120');
INSERT INTO `prueba` VALUES (122,'nombre 121');
INSERT INTO `prueba` VALUES (123,'nombre 122');
INSERT INTO `prueba` VALUES (124,'nombre 123');
INSERT INTO `prueba` VALUES (125,'nombre 124');
INSERT INTO `prueba` VALUES (126,'nombre 125');
INSERT INTO `prueba` VALUES (127,'nombre 126');
INSERT INTO `prueba` VALUES (128,'nombre 127');
INSERT INTO `prueba` VALUES (129,'nombre 128');
INSERT INTO `prueba` VALUES (130,'nombre 129');
INSERT INTO `prueba` VALUES (131,'nombre 130');
INSERT INTO `prueba` VALUES (132,'nombre 131');
INSERT INTO `prueba` VALUES (133,'nombre 132');
INSERT INTO `prueba` VALUES (134,'nombre 133');
INSERT INTO `prueba` VALUES (135,'nombre 134');
INSERT INTO `prueba` VALUES (136,'nombre 135');
INSERT INTO `prueba` VALUES (137,'nombre 136');
INSERT INTO `prueba` VALUES (138,'nombre 137');
INSERT INTO `prueba` VALUES (139,'nombre 138');
INSERT INTO `prueba` VALUES (140,'nombre 139');
INSERT INTO `prueba` VALUES (141,'nombre 140');
INSERT INTO `prueba` VALUES (142,'nombre 141');
INSERT INTO `prueba` VALUES (143,'nombre 142');
INSERT INTO `prueba` VALUES (144,'nombre 143');
INSERT INTO `prueba` VALUES (145,'nombre 144');
INSERT INTO `prueba` VALUES (146,'nombre 145');
INSERT INTO `prueba` VALUES (147,'nombre 146');
INSERT INTO `prueba` VALUES (148,'nombre 147');
INSERT INTO `prueba` VALUES (149,'nombre 148');
INSERT INTO `prueba` VALUES (150,'nombre 149');
INSERT INTO `prueba` VALUES (151,'nombre 150');
INSERT INTO `prueba` VALUES (152,'nombre 151');
INSERT INTO `prueba` VALUES (153,'nombre 152');
INSERT INTO `prueba` VALUES (154,'nombre 153');
INSERT INTO `prueba` VALUES (155,'nombre 154');
INSERT INTO `prueba` VALUES (156,'nombre 155');
INSERT INTO `prueba` VALUES (157,'nombre 156');
INSERT INTO `prueba` VALUES (158,'nombre 157');
INSERT INTO `prueba` VALUES (159,'nombre 158');
INSERT INTO `prueba` VALUES (160,'nombre 159');
INSERT INTO `prueba` VALUES (161,'nombre 160');
INSERT INTO `prueba` VALUES (162,'nombre 161');
INSERT INTO `prueba` VALUES (163,'nombre 162');
INSERT INTO `prueba` VALUES (164,'nombre 163');
INSERT INTO `prueba` VALUES (165,'nombre 164');
INSERT INTO `prueba` VALUES (166,'nombre 165');
INSERT INTO `prueba` VALUES (167,'nombre 166');
INSERT INTO `prueba` VALUES (168,'nombre 167');
INSERT INTO `prueba` VALUES (169,'nombre 168');
INSERT INTO `prueba` VALUES (170,'nombre 169');
INSERT INTO `prueba` VALUES (171,'nombre 170');
INSERT INTO `prueba` VALUES (172,'nombre 171');
INSERT INTO `prueba` VALUES (173,'nombre 172');
INSERT INTO `prueba` VALUES (174,'nombre 173');
INSERT INTO `prueba` VALUES (175,'nombre 174');
INSERT INTO `prueba` VALUES (176,'nombre 175');
INSERT INTO `prueba` VALUES (177,'nombre 176');
INSERT INTO `prueba` VALUES (178,'nombre 177');
INSERT INTO `prueba` VALUES (179,'nombre 178');
INSERT INTO `prueba` VALUES (180,'nombre 179');
INSERT INTO `prueba` VALUES (181,'nombre 180');
INSERT INTO `prueba` VALUES (182,'nombre 181');
INSERT INTO `prueba` VALUES (183,'nombre 182');
INSERT INTO `prueba` VALUES (184,'nombre 183');
INSERT INTO `prueba` VALUES (185,'nombre 184');
INSERT INTO `prueba` VALUES (186,'nombre 185');
INSERT INTO `prueba` VALUES (187,'nombre 186');
INSERT INTO `prueba` VALUES (188,'nombre 187');
INSERT INTO `prueba` VALUES (189,'nombre 188');
INSERT INTO `prueba` VALUES (190,'nombre 189');
INSERT INTO `prueba` VALUES (191,'nombre 190');
INSERT INTO `prueba` VALUES (192,'nombre 191');
INSERT INTO `prueba` VALUES (193,'nombre 192');
INSERT INTO `prueba` VALUES (194,'nombre 193');
INSERT INTO `prueba` VALUES (195,'nombre 194');
INSERT INTO `prueba` VALUES (196,'nombre 195');
INSERT INTO `prueba` VALUES (197,'nombre 196');
INSERT INTO `prueba` VALUES (198,'nombre 197');
INSERT INTO `prueba` VALUES (199,'nombre 198');
INSERT INTO `prueba` VALUES (200,'nombre 199');
INSERT INTO `prueba` VALUES (201,'nombre 200');
INSERT INTO `prueba` VALUES (202,'nombre 201');
INSERT INTO `prueba` VALUES (203,'nombre 202');
INSERT INTO `prueba` VALUES (204,'nombre 203');
INSERT INTO `prueba` VALUES (205,'nombre 204');
INSERT INTO `prueba` VALUES (206,'nombre 205');
INSERT INTO `prueba` VALUES (207,'nombre 206');
INSERT INTO `prueba` VALUES (208,'nombre 207');
INSERT INTO `prueba` VALUES (209,'nombre 208');
INSERT INTO `prueba` VALUES (210,'nombre 209');
INSERT INTO `prueba` VALUES (211,'nombre 210');
INSERT INTO `prueba` VALUES (212,'nombre 211');
INSERT INTO `prueba` VALUES (213,'nombre 212');
INSERT INTO `prueba` VALUES (214,'nombre 213');
INSERT INTO `prueba` VALUES (215,'nombre 214');
INSERT INTO `prueba` VALUES (216,'nombre 215');
INSERT INTO `prueba` VALUES (217,'nombre 216');
INSERT INTO `prueba` VALUES (218,'nombre 217');
INSERT INTO `prueba` VALUES (219,'nombre 218');
INSERT INTO `prueba` VALUES (220,'nombre 219');
INSERT INTO `prueba` VALUES (221,'nombre 220');
INSERT INTO `prueba` VALUES (222,'nombre 221');
INSERT INTO `prueba` VALUES (223,'nombre 222');
INSERT INTO `prueba` VALUES (224,'nombre 223');
INSERT INTO `prueba` VALUES (225,'nombre 224');
INSERT INTO `prueba` VALUES (226,'nombre 225');
INSERT INTO `prueba` VALUES (227,'nombre 226');
INSERT INTO `prueba` VALUES (228,'nombre 227');
INSERT INTO `prueba` VALUES (229,'nombre 228');
INSERT INTO `prueba` VALUES (230,'nombre 229');
INSERT INTO `prueba` VALUES (231,'nombre 230');
INSERT INTO `prueba` VALUES (232,'nombre 231');
INSERT INTO `prueba` VALUES (233,'nombre 232');
INSERT INTO `prueba` VALUES (234,'nombre 233');
INSERT INTO `prueba` VALUES (235,'nombre 234');
INSERT INTO `prueba` VALUES (236,'nombre 235');
INSERT INTO `prueba` VALUES (237,'nombre 236');
INSERT INTO `prueba` VALUES (238,'nombre 237');
INSERT INTO `prueba` VALUES (239,'nombre 238');
INSERT INTO `prueba` VALUES (240,'nombre 239');
INSERT INTO `prueba` VALUES (241,'nombre 240');
INSERT INTO `prueba` VALUES (242,'nombre 241');
INSERT INTO `prueba` VALUES (243,'nombre 242');
INSERT INTO `prueba` VALUES (244,'nombre 243');
INSERT INTO `prueba` VALUES (245,'nombre 244');
INSERT INTO `prueba` VALUES (246,'nombre 245');
INSERT INTO `prueba` VALUES (247,'nombre 246');
INSERT INTO `prueba` VALUES (248,'nombre 247');
INSERT INTO `prueba` VALUES (249,'nombre 248');
INSERT INTO `prueba` VALUES (250,'nombre 249');
INSERT INTO `prueba` VALUES (251,'nombre 250');
INSERT INTO `prueba` VALUES (252,'nombre 251');
INSERT INTO `prueba` VALUES (253,'nombre 252');
INSERT INTO `prueba` VALUES (254,'nombre 253');
INSERT INTO `prueba` VALUES (255,'nombre 254');
INSERT INTO `prueba` VALUES (256,'nombre 255');
INSERT INTO `prueba` VALUES (257,'nombre 256');
INSERT INTO `prueba` VALUES (258,'nombre 257');
INSERT INTO `prueba` VALUES (259,'nombre 258');
INSERT INTO `prueba` VALUES (260,'nombre 259');
INSERT INTO `prueba` VALUES (261,'nombre 260');
INSERT INTO `prueba` VALUES (262,'nombre 261');
INSERT INTO `prueba` VALUES (263,'nombre 262');
INSERT INTO `prueba` VALUES (264,'nombre 263');
INSERT INTO `prueba` VALUES (265,'nombre 264');
INSERT INTO `prueba` VALUES (266,'nombre 265');
INSERT INTO `prueba` VALUES (267,'nombre 266');
INSERT INTO `prueba` VALUES (268,'nombre 267');
INSERT INTO `prueba` VALUES (269,'nombre 268');
INSERT INTO `prueba` VALUES (270,'nombre 269');
INSERT INTO `prueba` VALUES (271,'nombre 270');
INSERT INTO `prueba` VALUES (272,'nombre 271');
INSERT INTO `prueba` VALUES (273,'nombre 272');
INSERT INTO `prueba` VALUES (274,'nombre 273');
INSERT INTO `prueba` VALUES (275,'nombre 274');
INSERT INTO `prueba` VALUES (276,'nombre 275');
INSERT INTO `prueba` VALUES (277,'nombre 276');
INSERT INTO `prueba` VALUES (278,'nombre 277');
INSERT INTO `prueba` VALUES (279,'nombre 278');
INSERT INTO `prueba` VALUES (280,'nombre 279');
INSERT INTO `prueba` VALUES (281,'nombre 280');
INSERT INTO `prueba` VALUES (282,'nombre 281');
INSERT INTO `prueba` VALUES (283,'nombre 282');
INSERT INTO `prueba` VALUES (284,'nombre 283');
INSERT INTO `prueba` VALUES (285,'nombre 284');
INSERT INTO `prueba` VALUES (286,'nombre 285');
INSERT INTO `prueba` VALUES (287,'nombre 286');
INSERT INTO `prueba` VALUES (288,'nombre 287');
INSERT INTO `prueba` VALUES (289,'nombre 288');
INSERT INTO `prueba` VALUES (290,'nombre 289');
INSERT INTO `prueba` VALUES (291,'nombre 290');
INSERT INTO `prueba` VALUES (292,'nombre 291');
INSERT INTO `prueba` VALUES (293,'nombre 292');
INSERT INTO `prueba` VALUES (294,'nombre 293');
INSERT INTO `prueba` VALUES (295,'nombre 294');
INSERT INTO `prueba` VALUES (296,'nombre 295');
INSERT INTO `prueba` VALUES (297,'nombre 296');
INSERT INTO `prueba` VALUES (298,'nombre 297');
INSERT INTO `prueba` VALUES (299,'nombre 298');
INSERT INTO `prueba` VALUES (300,'nombre 299');
/*!40000 ALTER TABLE `prueba` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for table usuarios
#
DROP TABLE IF EXISTS `usuarios`;
CREATE TABLE `usuarios` (
`id` int(4) unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(100) CHARACTER SET latin1 NOT NULL,
`usuario` varchar(30) CHARACTER SET latin1 NOT NULL,
`pass` varchar(40) CHARACTER SET latin1 NOT NULL,
`email` varchar(100) CHARACTER SET latin1 NOT NULL,
`role` enum('admin','especial','usuario') CHARACTER SET latin1 NOT NULL DEFAULT 'admin',
`estado` tinyint(4) DEFAULT NULL,
`fecha` datetime DEFAULT NULL,
`codigo` int(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `codigo` (`codigo`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
#
# Dumping data for table usuarios
#
LOCK TABLES `usuarios` WRITE;
/*!40000 ALTER TABLE `usuarios` DISABLE KEYS */;
INSERT INTO `usuarios` VALUES (1,'nombre1','admin','d1b254c9620425f582e27f0044be34bee087d8b4','admin@localhost.com','admin',1,NULL,NULL);
INSERT INTO `usuarios` VALUES (2,'usuario1','usuario','d1b254c9620425f582e27f0044be34bee087d8b4','usuario@hotmail.com','usuario',1,NULL,NULL);
INSERT INTO `usuarios` VALUES (3,'especial1','especial','d1b254c9620425f582e27f0044be34bee087d8b4','especial@hotmail.com','especial',1,NULL,NULL);
INSERT INTO `usuarios` VALUES (4,'Guillermo','grodriguez','d1b254c9620425f582e27f0044be34bee087d8b4','grodriguez@hotmail.com','admin',1,'2014-04-07 09:30:01',0);
INSERT INTO `usuarios` VALUES (5,'Carlos','carlos1','d1b254c9620425f582e27f0044be34bee087d8b4','g.rodriguezp@hotmail.com','usuario',1,'2014-04-07 16:47:54',1617216438);
INSERT INTO `usuarios` VALUES (6,'PETER','peter','eeb3980e639031f9c0906cd52e2239094e9ee612','petterherrera@hotmail.com','usuario',1,'2014-04-07 16:56:29',1492341464);
/*!40000 ALTER TABLE `usuarios` ENABLE KEYS */;
UNLOCK TABLES;
#
# Source for procedure sp_listaPost
#
DROP PROCEDURE IF EXISTS `sp_listaPost`;
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_listaPost`(
)
begin
select * from posts order by id desc;
end;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
| true |
3afffd60a9a26a801a1b46ce5cb32c45e9a80edb | SQL | donnevspankeren/MYSQL-BASIC | /opdracht/antwoorden.sql | UTF-8 | 1,573 | 3.046875 | 3 | [] | no_license | -- Opdracht 1
SELECT * FROM videogamesales WHERE 1
-- Opdracht 2
SELECT count(Name) AS alle_uitgebrachte_spellen_1999 FROM videogamesales WHERE year=1999
-- Opdracht 3
SELECT count(NA_Sales) AS Verkocht_in_NA FROM `videogamesales` WHERE genre="Sports"
-- Opdracht 4
SELECT name, platform FROM `videogamesales` WHERE publisher="Nintendo" AND year>1900 AND year<2005
-- Opdracht 5
SELECT name FROM `videogamesales` WHERE Global_Sales=8274;
-- Opdracht 6
SELECT avg(EU_Sales) AS Gemiddelde_verkocht_genre_puzzels FROM `videogamesales` WHERE genre="Puzzle"
-- Opdracht 7
SELECT name, genre, publisher FROM `videogamesales` WHERE JP_Sales=0
-- Opdracht 8
SELECT count(Global_Sales) AS Aantal_verkochte_spellen_Nintendo_wereldwijd FROM `videogamesales` WHERE publisher="Nintendo"
-- Opdracht 9
SELECT name, year FROM `videogamesales` WHERE genre="Racing" AND publisher="Nintendo" OR publisher="Activision"
-- Opdracht 10
SELECT avg(EU_Sales) AS Gemiddelde_verkochte_Europa, avg(JP_Sales) AS Gemiddelde_verkochte_Japan, avg(NA_Sales) AS Gemiddelde_verkochte_NA FROM `videogamesales` WHERE publisher="Sony Computer Entertainment" AND platform="PS4"
-- Opdracht 11
DELETE FROM videogamesales WHERE name="Halo 2" AND platform="XB"
-- Opdracht 12
DELETE FROM `videogamesales` WHERE year=2012 OR publisher="Ubisoft"
-- Opdracht 13
DELETE FROM `videogamesales` WHERE genre="Adventure" AND publisher="Nintendo"
-- Opdracht 14
DELETE FROM `videogamesales` WHERE publisher="Nintendo" AND Global_Sales<1000
-- Opdracht 15
DELETE FROM `videogamesales` WHERE year=1997 AND NA_Sales>200000 | true |
b3f520a5ef2233076bd881d15f03ce4d6b2dda40 | SQL | KeynesYouDigIt/PostgresTournament_DB_API | /tournament/tournament.sql | UTF-8 | 1,251 | 4.25 | 4 | [] | no_license | -- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
--
-- You can write comments in this file by starting them with two dashes, like
-- these lines here.
DROP DATABASE IF EXISTS tournament;
CREATE DATABASE tournament;
\c tournament
CREATE TABLE players (
p_id serial PRIMARY KEY,
name varchar(20),
ranking integer
);
CREATE TABLE match_ledger (
round_of_play integer NOT NULL,
match serial NOT NULL,
winner integer REFERENCES players (p_id),
loser integer REFERENCES players (p_id),
PRIMARY KEY (round_of_play, match)
);
CREATE VIEW players_by_wins AS
SELECT p.p_id, p.name,
count(ml_winner_count.winner) as win_count,
count(ml_match_count.winner + ml_match_count.loser) as matches
FROM players p
LEFT OUTER JOIN match_ledger ml_winner_count
ON p.p_id = ml_winner_count.winner
LEFT OUTER JOIN match_ledger ml_match_count
ON p.p_id = ml_match_count.winner OR p.p_id = ml_match_count.loser
GROUP BY p.p_id
ORDER BY win_count desc;
--example working insert
--INSERT INTO players (name, ranking) VALUES ("name", 1) | true |
e49eb6db3087b14283f0fd43bffda56bc735594e | SQL | maxclchen/myStrat.bk | /codes/MySQL/mysql.sql | UTF-8 | 1,237 | 3.703125 | 4 | [] | no_license | ## =============================================================================
## 主力合约的分钟数据
## =============================================================================
create table mainContractMinuteData(
TradingDay DATE NOT NULL,
Minute TIME NOT NULL,
NumericExchTime decimal(15,5) NULL,
InstrumentID varchar(100) NOT NULL,
ProductID varchar(100) NOT NULL,
open decimal(15,5) NULL,
high decimal(15,5) NULL,
low decimal(15,5) NULL,
close decimal(15,5) NULL,
volume INT NULL,
turnover decimal(30,5) NULL,
PRIMARY KEY (TradingDay, Minute, InstrumentID)
)
## -----------------------------------------------------------------------------
insert into mainContractMinuteData
SELECT a.TradingDay,
a.Minute,
a.NumericExchTime,
a.InstrumentID,
b.Product as ProductID,
a.OpenPrice as open,
a.HighPrice as high,
a.LowPrice as low,
a.ClosePrice as close,
a.Volume as volume,
a.Turnover as turnover
From minute as a,
main_contract_daily as b
WHERE a.TradingDay = b.TradingDay
AND a.InstrumentID = b.Main_contract;
| true |
c8d9a64d9e4aeaa04f9abc84be61ece98fb03c6c | SQL | walkandride/H1B-Visa-Project | /airflow/dags/create_staging_tables.sql | UTF-8 | 1,858 | 2.75 | 3 | [] | no_license | -- =============================================================================
-- Create staging tables for import files.
-- =============================================================================
CREATE TABLE IF NOT EXISTS stage_h1b_petitions(
id VARCHAR,
case_status VARCHAR,
employer_name VARCHAR,
soc_name VARCHAR,
job_title VARCHAR,
full_time_position VARCHAR,
prevailing_wage VARCHAR,
year VARCHAR,
worksite VARCHAR,
lon VARCHAR,
lat VARCHAR
);
CREATE TABLE IF NOT EXISTS stage_nationality(
year INT,
type VARCHAR,
nationality VARCHAR,
count INT
);
CREATE TABLE IF NOT EXISTS stage_min_wage(
year INT,
state VARCHAR,
table_data VARCHAR,
footnote VARCHAR,
hi_value VARCHAR,
lo_value VARCHAR,
cpi_avg VARCHAR,
hi_2018 VARCHAR,
lo_2018 VARCHAR
);
CREATE TABLE IF NOT EXISTS stage_world_happiness(
country VARCHAR,
year INT,
life_ladder NUMERIC,
log_gdp_per_capita NUMERIC,
social_support NUMERIC,
healthy_life_expectancy_at_birth NUMERIC,
freedom_to_make_life_choices NUMERIC,
generosity NUMERIC,
perceptions_of_corruption NUMERIC,
positive_affect NUMERIC,
negative_affect NUMERIC,
confidence_in_national_government NUMERIC,
democratic_quality NUMERIC,
delivery_quality NUMERIC,
standard_dev_of_ladder NUMERIC,
standard_dev_mean_of_ladder NUMERIC,
gini_index NUMERIC,
gini_index_est NUMERIC,
gini_of_household_income NUMERIC
);
CREATE TABLE IF NOT EXISTS stage_us_city_demographics(
city VARCHAR,
state VARCHAR,
median_age NUMERIC,
male_population INT,
female_population INT,
total_population INT,
number_of_veterans INT,
foreign_born INT,
average_household_size NUMERIC,
state_code VARCHAR,
race VARCHAR,
cnt INT
);
| true |
6feb6551d59a99ded9dad6ef6894dc9bb9f396f1 | SQL | Jotaii/Proyecto-Fisw | /fisw.sql | UTF-8 | 7,674 | 3.15625 | 3 | [] | no_license | -- MySQL dump 10.13 Distrib 5.6.30, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: fisw
-- ------------------------------------------------------
-- Server version 5.6.30-1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `Alumno`
--
DROP TABLE IF EXISTS `Alumno`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Alumno` (
`id_alumno` int(8) NOT NULL AUTO_INCREMENT,
`rut_alumno` varchar(13) NOT NULL,
`nombre_alumno` varchar(30) NOT NULL,
`apellido_p_alumno` varchar(50) NOT NULL,
`apellido_m_alumno` varchar(50) NOT NULL,
`nac_alumno` date NOT NULL,
`categoria_alumno` int(1) DEFAULT '0',
`foto_perfil_alumno` varchar(255) DEFAULT NULL,
`nombre_usuario` varchar(50) NOT NULL,
PRIMARY KEY (`id_alumno`),
UNIQUE KEY `id_alumno` (`id_alumno`),
UNIQUE KEY `rut_alumno` (`rut_alumno`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Alumno`
--
LOCK TABLES `Alumno` WRITE;
/*!40000 ALTER TABLE `Alumno` DISABLE KEYS */;
INSERT INTO `Alumno` VALUES (1,'000000010','Federico','Santa Maria','Carrera','1845-08-15',0,NULL,'');
/*!40000 ALTER TABLE `Alumno` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Contenido`
--
DROP TABLE IF EXISTS `Contenido`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Contenido` (
`id_contenido` int(10) NOT NULL AUTO_INCREMENT,
`multimedia` text,
`informacion` text,
`descripcion` text,
`categoria1_cont` int(1) NOT NULL DEFAULT '0',
`categoria2_cont` int(1) NOT NULL DEFAULT '0',
`categoria3_cont` int(1) NOT NULL DEFAULT '0',
`categoria4_cont` int(1) NOT NULL DEFAULT '0',
`id_ramo` int(10) NOT NULL,
UNIQUE KEY `id_contenido` (`id_contenido`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Contenido`
--
LOCK TABLES `Contenido` WRITE;
/*!40000 ALTER TABLE `Contenido` DISABLE KEYS */;
/*!40000 ALTER TABLE `Contenido` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Feedback`
--
DROP TABLE IF EXISTS `Feedback`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Feedback` (
`id_feedback` int(10) NOT NULL AUTO_INCREMENT,
`f_categoria` int(10) NOT NULL,
`f_esquema` int(10) NOT NULL,
`f_respuestas` varchar(255) NOT NULL,
`f_fecha_emision` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`id_ramo` int(10) NOT NULL,
`id_alumno` int(8) NOT NULL,
UNIQUE KEY `id_feedback` (`id_feedback`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Feedback`
--
LOCK TABLES `Feedback` WRITE;
/*!40000 ALTER TABLE `Feedback` DISABLE KEYS */;
/*!40000 ALTER TABLE `Feedback` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Profesor`
--
DROP TABLE IF EXISTS `Profesor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Profesor` (
`id_profesor` int(4) NOT NULL AUTO_INCREMENT,
`rut_profesor` varchar(13) NOT NULL,
`nombre_profesor` varchar(30) NOT NULL,
`apellido_p_profesor` varchar(50) NOT NULL,
`apellido_m_profesor` varchar(50) NOT NULL,
`nac_profesor` date NOT NULL,
`institucion_profesor` varchar(100) NOT NULL DEFAULT 'No informa',
`foto_perfil_profesor` varchar(255) DEFAULT NULL,
`nombre_usuario` varchar(50) NOT NULL,
PRIMARY KEY (`id_profesor`),
UNIQUE KEY `id_profesor` (`id_profesor`),
UNIQUE KEY `rut_profesor` (`rut_profesor`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Profesor`
--
LOCK TABLES `Profesor` WRITE;
/*!40000 ALTER TABLE `Profesor` DISABLE KEYS */;
/*!40000 ALTER TABLE `Profesor` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Profesor_Ramo`
--
DROP TABLE IF EXISTS `Profesor_Ramo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Profesor_Ramo` (
`Profesorid_profesor` int(4) NOT NULL,
`Ramoid_ramo` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Profesor_Ramo`
--
LOCK TABLES `Profesor_Ramo` WRITE;
/*!40000 ALTER TABLE `Profesor_Ramo` DISABLE KEYS */;
/*!40000 ALTER TABLE `Profesor_Ramo` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Ramo`
--
DROP TABLE IF EXISTS `Ramo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Ramo` (
`id_ramo` int(10) NOT NULL AUTO_INCREMENT,
`nombre_ramo` varchar(255) NOT NULL,
`semestre_ramo` varchar(6) NOT NULL,
`departamento` varchar(30) NOT NULL,
PRIMARY KEY (`id_ramo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Ramo`
--
LOCK TABLES `Ramo` WRITE;
/*!40000 ALTER TABLE `Ramo` DISABLE KEYS */;
/*!40000 ALTER TABLE `Ramo` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Ramo_Alumno`
--
DROP TABLE IF EXISTS `Ramo_Alumno`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Ramo_Alumno` (
`Ramoid_ramo` int(10) NOT NULL,
`Alumnoid_alumno` int(8) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Ramo_Alumno`
--
LOCK TABLES `Ramo_Alumno` WRITE;
/*!40000 ALTER TABLE `Ramo_Alumno` DISABLE KEYS */;
/*!40000 ALTER TABLE `Ramo_Alumno` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Usuario`
--
DROP TABLE IF EXISTS `Usuario`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Usuario` (
`nombre_usuario` varchar(50) NOT NULL,
`password_usuario` text NOT NULL,
`tipo_usuario` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`nombre_usuario`),
UNIQUE KEY `nombre_usuario` (`nombre_usuario`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Usuario`
--
LOCK TABLES `Usuario` WRITE;
/*!40000 ALTER TABLE `Usuario` DISABLE KEYS */;
/*!40000 ALTER TABLE `Usuario` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2016-09-09 14:01:55
| true |
2f6f18f04c3c4529195ee8b16cb3948fff24c446 | SQL | cloudtrainings/crate-workshop | /createtables_workshop_crate.sql | UTF-8 | 627 | 3.328125 | 3 | [] | no_license | CREATE TABLE IF NOT EXISTS workshop_weather (
city string,
temp_low integer,
temp_high integer,
prcp double,
datetime timestamp,
primary key (city, datetime)
)clustered by (city) into 6 shards
WITH (
number_of_replicas = '0-all',
refresh_interval = 1000
);
CREATE TABLE IF NOT EXISTS workshop_cities (
name string,
country string,
location geo_point,
primary key (name, country)
)clustered by (name) into 6 shards
WITH (
number_of_replicas = '0-all',
refresh_interval = 1000
); | true |
aad80609278ddec72644604effccad052972d8ec | SQL | jowclides/simplecrudcodeignter4 | /SQL/codeign_projetobase_updated.sql | UTF-8 | 3,003 | 2.921875 | 3 | [
"MIT"
] | permissive | -- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Tempo de geração: 04-Mar-2021 às 01:01
-- Versão do servidor: 10.4.17-MariaDB
-- versão do PHP: 8.0.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Banco de dados: `codeign_projetobase`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `news`
--
CREATE TABLE `news` (
`id` int(11) NOT NULL,
`title` varchar(128) NOT NULL,
`slug` varchar(128) NOT NULL,
`body` text NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`deleted_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Extraindo dados da tabela `news`
--
INSERT INTO `news` (`id`, `title`, `slug`, `body`, `created_at`, `updated_at`, `deleted_at`) VALUES
(4, 'Hospedagem PHP DNNETHOSTING/COUPLED', 'Hospedagem-PHP-DNNETHOSTINGCOUPLED', ' aaaaaaaa', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(5, 'Hospedagem PHP DNNETHOSTING/COUPLED', 'Hospedagem-PHP-DNNETHOSTINGCOUPLED', ' aaaaaaaa', '0000-00-00 00:00:00', '2021-03-03 17:34:38', '2021-03-03 17:34:38'),
(6, 'maravilha manooooaaaaaa', 'maravilha-manooooaaaaaa', 'oaoaoaooaa ', '0000-00-00 00:00:00', '2021-03-03 17:35:02', '2021-03-03 17:35:02'),
(8, 'maravilha manoooo', 'maravilha-manoooo', 'oaoaoaooaa ', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(11, 'Hospedagem PHP DNNETHOSTING/COUPLED sasassasasasas', 'Hospedagem-PHP-DNNETHOSTINGCOUPLED-sasassasasasas', ' asasaasasasasasasasa', '0000-00-00 00:00:00', '2021-03-03 17:34:35', '2021-03-03 17:34:35'),
(14, 'Noticia muito BBB', 'Noticia-muito-BBB', 'Noticia muito BBB', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(15, 'asaasasaas 1', 'asaasasaas-1', 'asaasasaas 1', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(16, 'DA hora 1', 'DA-hora-1', 'DA hora 1', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(17, 'Teste final', 'Teste-final', 'asasasas', '2021-03-03 17:31:25', '2021-03-03 17:31:25', '0000-00-00 00:00:00'),
(18, 'asasa', 'asasa', 'sassa', '2021-03-03 17:32:03', '2021-03-03 17:49:03', '2021-03-03 17:49:03');
--
-- Índices para tabelas despejadas
--
--
-- Índices para tabela `news`
--
ALTER TABLE `news`
ADD PRIMARY KEY (`id`),
ADD KEY `slug` (`slug`);
--
-- AUTO_INCREMENT de tabelas despejadas
--
--
-- AUTO_INCREMENT de tabela `news`
--
ALTER TABLE `news`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
c2fb16116465e97a333cffd94f2af692f1c56927 | SQL | zjuphoenix/health-monitor | /src/main/resources/mysql.sql | UTF-8 | 1,448 | 3.125 | 3 | [] | no_license | USE artificial_liver;
CREATE TABLE user(
id INT(4) not null primary key auto_increment,
username VARCHAR(40) not null,
gender VARCHAR(2) not null,
password VARCHAR(40),
tel VARCHAR(20),
mail VARCHAR(30)
);
SELECT * FROM users WHERE username = #{username} LIMIT 1;
CREATE TABLE bloodoxygen(
userId INT COMMENT '用户id',
timestamp LONG NOT NULL COMMENT '时间戳',
pulse_rate INT COMMENT '脉率',
saturation VARCHAR(10) COMMENT '饱和度',
pulse_intensity INT COMMENT '脉搏强度',
status BOOL COMMENT '是否异常'
);
CREATE TABLE bloodpressure(
userId INT COMMENT '用户id',
timestamp LONG NOT NULL COMMENT '时间戳',
systolic_pressure INT COMMENT '收缩压',
diastolic_pressure INT COMMENT '舒张压',
mean_pressure INT COMMENT '平均压',
pulse_rate INT COMMENT '脉率',
status BOOL COMMENT '是否异常'
);
CREATE TABLE ecg(
userId INT COMMENT '用户id',
timestamp LONG NOT NULL COMMENT '时间戳',
breath_rate INT COMMENT '呼吸率',
heart_rate INT COMMENT '心率',
status BOOL COMMENT '是否异常'
);
CREATE TABLE bloodsugar(
userId INT COMMENT '用户id',
timestamp LONG NOT NULL COMMENT '时间戳',
blood_sugar INT COMMENT '血糖',
status BOOL COMMENT '是否异常'
);
CREATE TABLE bloodketone(
userId INT COMMENT '用户id',
timestamp LONG NOT NULL COMMENT '时间戳',
blood_ketone INT COMMENT '血酮',
status BOOL COMMENT '是否异常'
);
| true |
d3e32967cb4719ba40ef340fe805669c8a1109ff | SQL | pulsetracker/W205 | /exercise_1/investigations/hospital_variability/hospital_variablility.sql | UTF-8 | 530 | 3.6875 | 4 | [] | no_license |
-- Based on Effective Care score (high is good)
SELECT COUNT(ecscore), ROUND(AVG(cast(ecscore as INT))), ROUND(STDDEV(cast(ecscore as INT))) AS A1, measure_name
FROM TxProcedures
WHERE (CAST(ecscore AS INT) IS NOT NULL)
GROUP BY measure_name
ORDER BY A1 DESC
LIMIT 10;
-- Based on Readmission (Low is good)
SELECT COUNT(rscore), ROUND(AVG(cast(rscore as INT))), (STDDEV(cast(rscore as INT))) as A2, measure_name
FROM TxProcedures
WHERE (CAST(rscore AS INT) IS NOT NULL)
GROUP BY measure_name
ORDER BY A2 DESC
LIMIT 10;
| true |
175e95930eafb9f105e3cfeaa493741b092b8080 | SQL | pythonoras/Toontown-Private-Server-Webend | /conf/evolutions/default/17.sql | UTF-8 | 787 | 3.34375 | 3 | [] | no_license | # --- !Ups
create table toon_name (
id integer auto_increment not null,
toon_id integer,
user_id integer,
candidate_name varchar(255),
current_name varchar(255),
received datetime,
processed datetime,
submitted datetime,
was_rejected tinyint(1) default 0,
constraint pk_toon_name primary key (id))
;
alter table registration_key add column `generator_id` integer;
alter table registration_key add column `generated` datetime;
# --- !Downs
SET FOREIGN_KEY_CHECKS=0;
drop table toon_name;
alter table registration_key drop column `generator_id`;
alter table registration_key drop column `generated`;
SET FOREIGN_KEY_CHECKS=1; | true |
368ca4031eceb1187c940dfa4ce3eb32181ba81e | SQL | kreid333/myblog | /seeds.sql | UTF-8 | 603 | 3.140625 | 3 | [
"MIT"
] | permissive | DROP TABLE IF EXISTS posts;
DROP TABLE IF EXISTS accounts;
CREATE TABLE posts(
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
user_id VARCHAR(255) NOT NULL,
username VARCHAR(255) NOT NULL,
img VARCHAR(255) NOT NULL,
date VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
content VARCHAR(5000) NOT NULL,
tag VARCHAR(255) NOT NULL
);
CREATE TABLE accounts (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
user_id varchar(50) UNIQUE NOT NULL,
email varchar(100) UNIQUE NOT NULL,
username varchar(50) UNIQUE NOT NULL,
password varchar(255) UNIQUE NOT NULL
); | true |
c06bae5fe17657f1b6ed250cd81f8b17f9caddc5 | SQL | reanrean/LeetCode | /585_Investments_in_2016.sql | UTF-8 | 316 | 3.9375 | 4 | [] | no_license | select sum(tiv_2016) as tiv_2016
from insurance i
inner join
(select tiv_2015
from insurance
group by tiv_2015
having count(1) > 1)a on a.tiv_2015 = i.tiv_2015
inner join
(select concat(lat,lon) as location, count(1)
from insurance
group by concat(lat,lon)
having count(1) = 1) b on b.location = concat(i.lat,i.lon) | true |
c5d6c83107d1f0cb4ea5e28739bff87ab0069caf | SQL | artcom1/test | /#DB/struct/fkconstraint.mv.sql | UTF-8 | 1,706 | 2.90625 | 3 | [] | no_license | ALTER TABLE ONLY ts_multivalfiltr
ADD CONSTRAINT ts_multivalfiltr_mvs_id_fkey FOREIGN KEY (mvs_id) REFERENCES ts_multivals(mvs_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
--
ALTER TABLE ONLY ts_multivals
ADD CONSTRAINT ts_multivals_mvg_id_fkey FOREIGN KEY (mvg_id) REFERENCES ts_multivalpage(mvg_id) ON UPDATE CASCADE ON DELETE RESTRICT;
--
--
ALTER TABLE ONLY ts_multivals
ADD CONSTRAINT ts_multivals_mvs_ex_idslownika_fkey FOREIGN KEY (mvs_ex_idslownika) REFERENCES public.tg_slownik(sl_idslownika) ON UPDATE CASCADE ON DELETE RESTRICT;
--
--
ALTER TABLE ONLY ts_multivals
ADD CONSTRAINT ts_multivals_mvs_idslownikarozmiarowki_fkey FOREIGN KEY (mvs_idslownikarozmiarowki) REFERENCES public.tg_rozmrodzaje(rmr_idrodzaju) ON UPDATE CASCADE ON DELETE RESTRICT;
--
--
ALTER TABLE ONLY ts_mvmoveables
ADD CONSTRAINT ts_mvmoveables_mvs_dstid_fkey FOREIGN KEY (mvs_dstid) REFERENCES ts_multivals(mvs_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
--
ALTER TABLE ONLY ts_mvmoveables
ADD CONSTRAINT ts_mvmoveables_mvs_srcid_fkey FOREIGN KEY (mvs_srcid) REFERENCES ts_multivals(mvs_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
--
ALTER TABLE ONLY ts_mvpodrodzaj
ADD CONSTRAINT ts_mvpodrodzaj_mvs_id_fkey FOREIGN KEY (mvs_id) REFERENCES ts_multivals(mvs_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
--
ALTER TABLE ONLY ts_mvzestawelem
ADD CONSTRAINT ts_mvzestawelem_mvs_id_fkey FOREIGN KEY (mvs_id) REFERENCES ts_multivals(mvs_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
--
ALTER TABLE ONLY ts_mvzestawelem
ADD CONSTRAINT ts_mvzestawelem_mvz_idzestawu_fkey FOREIGN KEY (mvz_idzestawu) REFERENCES ts_mvzestaw(mvz_idzestawu) ON UPDATE CASCADE ON DELETE CASCADE;
| true |
a18954b9cef35ea3ec52547b28d33df1cff23a63 | SQL | bellmit/flexdb | /2.HOST/3.Procedure/od0023.sql | UTF-8 | 10,233 | 3.375 | 3 | [] | no_license | CREATE OR REPLACE PROCEDURE od0023 (
PV_REFCURSOR IN OUT PKG_REPORT.REF_CURSOR,
OPT IN VARCHAR2,
BRID IN VARCHAR2,
F_DATE IN VARCHAR2,
T_DATE IN VARCHAR2,
SYMBOL IN VARCHAR2,
EXECTYPE IN VARCHAR2,
TRADEPLACE IN VARCHAR2,
VOUCHER IN VARCHAR2,
TYPEORDER IN VARCHAR2,
PRICETYPE IN VARCHAR2
)
IS
--
-- PURPOSE: BRIEFLY EXPLAIN THE FUNCTIONALITY OF THE PROCEDURE
-- TONG HOP KET QUA KHOP LENH
-- MODIFICATION HISTORY
-- PERSON DATE COMMENTS
-- NAMNT 21-NOV-06 CREATED
-- --------- ------ -------------------------------------------
V_STROPTION VARCHAR2 (5); -- A: ALL; B: BRANCH; S: SUB-BRANCH
V_STRBRID VARCHAR2 (4); -- USED WHEN V_NUMOPTION > 0
V_STREXECTYPE VARCHAR2 (5);
V_STRSYMBOL VARCHAR2 (30);
V_STRTRADEPLACE VARCHAR2 (3);
V_STRVOUCHER VARCHAR2 (3);
V_STRTYPEORDER VARCHAR2 (3);
--ThanhTC sua them tham so PriceType, va tinh phi
V_STRPRICETYPE VARCHAR2 (10);
V_NUMFEEACR NUMBER;
V_NUMFEEACR_BRO NUMBER;
V_NUMFEE_TD NUMBER;
CUR PKG_REPORT.REF_CURSOR;
--ThanhTC end.
-- DECLARE PROGRAM VARIABLES AS SHOWN ABOVE
BEGIN
V_STROPTION := OPT;
IF (V_STROPTION <> 'A') AND (BRID <> 'ALL')
THEN
V_STRBRID := BRID;
ELSE
V_STRBRID := '%%';
END IF;
-- GET REPORT'S PARAMETERS
IF (TRADEPLACE <> 'ALL')
THEN
V_STRTRADEPLACE := TRADEPLACE;
ELSE
V_STRTRADEPLACE := '%%';
END IF;
--
IF (SYMBOL <> 'ALL')
THEN
V_STRSYMBOL :=replace(SYMBOL,' ','_');
ELSE
V_STRSYMBOL := '%%';
END IF;
--
IF (EXECTYPE <> 'ALL')
THEN
V_STREXECTYPE := EXECTYPE;
ELSE
V_STREXECTYPE := '%%';
END IF;
IF (VOUCHER <> 'ALL')
THEN
V_STRVOUCHER := VOUCHER;
ELSE
V_STRVOUCHER := '%%';
END IF;
IF (TYPEORDER <> 'ALL')
THEN
V_STRTYPEORDER := TYPEORDER;
ELSE
V_STRTYPEORDER := '%%';
END IF;
IF (PRICETYPE <> 'ALL')
THEN
V_STRPRICETYPE := PRICETYPE;
ELSE
V_STRPRICETYPE := '%%';
END IF;
--- TINH TONG PHI
OPEN CUR
FOR
SELECT NVL(SUM(AMT.FEEACR),0)
FROM (
SELECT SUM(FEEACR) FEEACR FROM ODMAST,(SELECT * FROM SBSECURITIES WHERE SYMBOL LIKE V_STRSYMBOL AND TRADEPLACE LIKE V_STRTRADEPLACE)sb
WHERE DELTD <>'Y'
AND TXDATE <= TO_DATE (T_DATE ,'DD/MM/YYYY') AND TXDATE >= TO_DATE (F_DATE ,'DD/MM/YYYY')
AND EXECTYPE LIKE V_STREXECTYPE AND ODMAST.CODEID=SB.CODEID
AND VOUCHER LIKE V_STRVOUCHER AND PRICETYPE LIKE V_STRPRICETYPE
UNION ALL
SELECT SUM(FEEACR) FEEACR FROM ODMASTHIST,(SELECT * FROM SBSECURITIES WHERE SYMBOL LIKE V_STRSYMBOL AND TRADEPLACE LIKE V_STRTRADEPLACE)sb WHERE DELTD <>'Y'
AND TXDATE <= TO_DATE (T_DATE ,'DD/MM/YYYY') AND TXDATE >= TO_DATE (F_DATE ,'DD/MM/YYYY')
AND EXECTYPE LIKE V_STREXECTYPE AND VOUCHER LIKE V_STRTYPEORDER
AND PRICETYPE LIKE V_STRPRICETYPE
AND ODMASTHIST.CODEID=SB.CODEID
)AMT
;
LOOP
FETCH CUR
INTO V_NUMFEEACR ;
EXIT WHEN CUR%NOTFOUND;
END LOOP;
CLOSE CUR;
--KET THUC TINH TONG PHI
--- TINH TONG PHI MOI GIOI
OPEN CUR
FOR
SELECT NVL(SUM(AMT.FEEACR),0)
FROM (
SELECT SUM(FEEACR) FEEACR FROM ODMAST,(SELECT * FROM SBSECURITIES WHERE SYMBOL LIKE V_STRSYMBOL AND TRADEPLACE LIKE V_STRTRADEPLACE)sb WHERE DELTD <>'Y'
AND TXDATE <= TO_DATE (T_DATE ,'DD/MM/YYYY') AND TXDATE >= TO_DATE (F_DATE ,'DD/MM/YYYY')
AND AFACCTNO NOT IN('0001222222')AND ODMAST.CODEID=SB.CODEID
AND EXECTYPE LIKE V_STREXECTYPE AND VOUCHER LIKE V_STRVOUCHER AND PRICETYPE LIKE V_STRPRICETYPE
UNION ALL
SELECT SUM(FEEACR) FEEACR FROM ODMASTHIST,(SELECT * FROM SBSECURITIES WHERE SYMBOL LIKE V_STRSYMBOL AND TRADEPLACE LIKE V_STRTRADEPLACE)sb WHERE DELTD <>'Y'
AND TXDATE <= TO_DATE (T_DATE ,'DD/MM/YYYY') AND TXDATE >= TO_DATE (F_DATE ,'DD/MM/YYYY')
AND AFACCTNO NOT IN('0001222222')AND ODMASTHIST.CODEID=SB.CODEID
AND EXECTYPE LIKE V_STREXECTYPE AND VOUCHER LIKE V_STRVOUCHER AND PRICETYPE LIKE V_STRPRICETYPE
)AMT
;
LOOP
FETCH CUR
INTO V_NUMFEEACR_BRO ;
EXIT WHEN CUR%NOTFOUND;
END LOOP;
CLOSE CUR;
--KET THUC TINH PHI MOI GIOI
--- TINH GIA TRI KHOP TU DOANH
OPEN CUR
FOR
SELECT NVL(SUM(IO.MATCHPRICE*IO.MATCHQTTY),0) FROM
(
SELECT * FROM ODMAST WHERE DELTD <>'Y'
AND TXDATE <= TO_DATE (T_DATE ,'DD/MM/YYYY') AND TXDATE >= TO_DATE (F_DATE ,'DD/MM/YYYY')
AND EXECTYPE LIKE V_STREXECTYPE AND VOUCHER LIKE V_STRVOUCHER
AND PRICETYPE LIKE V_STRPRICETYPE AND AFACCTNO LIKE '0001222222'
UNION ALL
SELECT * FROM ODMASTHIST WHERE DELTD <>'Y'
AND TXDATE <= TO_DATE (T_DATE ,'DD/MM/YYYY') AND TXDATE >= TO_DATE (F_DATE ,'DD/MM/YYYY')
AND EXECTYPE LIKE V_STREXECTYPE AND VOUCHER LIKE V_STRVOUCHER
AND PRICETYPE LIKE V_STRPRICETYPE AND AFACCTNO LIKE '0001222222'
) OD ,
(SELECT * FROM IOD UNION ALL SELECT * FROM IODHIST)IO,
(SELECT * FROM SBSECURITIES WHERE SYMBOL LIKE V_STRSYMBOL AND TRADEPLACE LIKE V_STRTRADEPLACE)sb
WHERE OD.ORDERID= IO.ORGORDERID AND OD.CODEID=SB.CODEID
;
LOOP
FETCH CUR
INTO V_NUMFEE_TD ;
EXIT WHEN CUR%NOTFOUND;
END LOOP;
CLOSE CUR;
--KET THUC TINH GIA TRI KHOP TU DOANH
OPEN PV_REFCURSOR
FOR
SELECT V_NUMFEEACR V_NUMFEEACR, V_NUMFEEACR_BRO V_NUMFEEACR_BRO,V_NUMFEE_TD V_NUMFEE_TD,OD.*
FROM
( SELECT OD.ORDERID,OD.TXDATE,SB.SYMBOL,OD.ORDERQTTY,OD.QUOTEPRICE,OD.CIACCTNO,CF.FULLNAME,
SB.TRADEPLACE TRADEPLACE,CF.CUSTODYCD,od.VOUCHER,
(CASE when TL.TLTXCD IN ('8882','8883','8884','8885') THEN 'C' ELSE od.EXECTYPE END)EXTY,od.EXECTYPE,
(CASE when TL.TLTXCD IN ('8882','8883','8884','8885') THEN 'C' else 'O' END ) TYORDER,round(STS.AMT/STS.QTTY) MATCHPRICE, STS.QTTY MATCHQTTY,
(CASE WHEN STS.MARK =1 THEN OD.FEEACR ELSE 0 END ) FEEACR
FROM
(select * from odmast where deltd<>'Y' union ALL SELECT * FROM odmasthist where deltd<>'Y')od,
(SELECT STS.* , (CASE WHEN STS.AUTOID=STS_MAX.AUTOID THEN 1 ELSE 0 END) MARK FROM
(SELECT * FROM STSCHD WHERE DELTD <>'Y'AND DUETYPE IN ('SS','SM') UNION ALL
SELECT * FROM STSCHDHIST WHERE DELTD <>'Y'AND DUETYPE IN ('SS','SM'))STS,
(SELECT MAX(AUTOID) AUTOID,ORGORDERID FROM STSCHDHIST WHERE DUETYPE IN ('SS','SM') AND DELTD <>'Y' GROUP BY ORGORDERID
UNION ALL
SELECT MAX(AUTOID) AUTOID,ORGORDERID FROM STSCHD WHERE DUETYPE IN ('SS','SM') AND DELTD <>'Y' GROUP BY ORGORDERID )STS_MAX
WHERE STS.ORGORDERID = STS_MAX.ORGORDERID
ORDER BY STS.ORGORDERID)STS,
(select * from tllog where deltd <> 'Y' UNION ALL select * from tllogall where deltd <> 'Y' )tl,
SBSECURITIES SB,AFMAST AF ,CFMAST CF
where TL.TXDATE = OD.TXDATE AND TL.TXNUM=OD.TXNUM
and OD.ORDERID =STS.ORGORDERID
AND OD.CIACCTNO=AF.ACCTNO
AND AF.CUSTID=CF.CUSTID
AND OD.CODEID=SB.CODEID
AND OD.TXDATE >= TO_DATE (F_DATE, 'DD/MM/YYYY')
AND OD.TXDATE <= TO_DATE (T_DATE, 'DD/MM/YYYY')
AND SB.SYMBOL LIKE V_STRSYMBOL
AND OD.EXECTYPE LIKE V_STREXECTYPE
AND SB.TRADEPLACE LIKE V_STRTRADEPLACE
AND SUBSTR (OD.AFACCTNO, 1, 4) LIKE V_STRBRID
and od.VOUCHER like V_STRVOUCHER) OD
WHERE OD.TYORDER LIKE V_STRTYPEORDER
ORDER BY OD.CIACCTNO, OD.TXDATE , OD.ORDERID;
/*/
ELSE
OPEN PV_REFCURSOR
FOR
SELECT V_NUMFEEACR V_NUMFEEACR, V_NUMFEEACR_BRO V_NUMFEEACR_BRO , V_NUMFEE_TD V_NUMFEE_TD, T.*,NVL(IO.MATCHQTTY,0) MATCHQTTY,NVL(IO.MATCHPRICE,0) MATCHPRICE FROM
(SELECT OD.ORDERID,OD.TXDATE,SB.SYMBOL, (CASE WHEN OD.PRICETYPE IN ('ATO','ATC')THEN OD.PRICETYPE ELSE TO_CHAR(OD.QUOTEPRICE) END )QUOTEPRICE ,
OD.ORDERQTTY, OD.CIACCTNO,CF.FULLNAME,OD.FEEACR,
SB.TRADEPLACE TRADEPLACE,CF.CUSTODYCD,od.VOUCHER,
(CASE when TL.TLTXCD IN ('8882','8883','8884','8885') THEN 'C' ELSE od.EXECTYPE END)EXTY,od.EXECTYPE,
(CASE when TL.TLTXCD IN ('8882','8883','8884','8885') THEN 'C' else 'O' END ) TYORDER
FROM (SELECT* FROM ODMAST
WHERE TXDATE >= TO_DATE (F_DATE, 'DD/MM/YYYY')
AND TXDATE <= TO_DATE (T_DATE, 'DD/MM/YYYY')
UNION ALL
SELECT * FROM ODMASTHIST
WHERE TXDATE >= TO_DATE (F_DATE, 'DD/MM/YYYY')
AND TXDATE <= TO_DATE (T_DATE, 'DD/MM/YYYY')
)OD,
(SELECT * FROM TLLOG
WHERE DELTD<>'Y'
AND TXDATE >= TO_DATE (F_DATE, 'DD/MM/YYYY')
AND TXDATE <= TO_DATE (T_DATE, 'DD/MM/YYYY')
UNION ALL
SELECT * FROM TLLOGALL
WHERE DELTD<>'Y'
AND TXDATE >= TO_DATE (F_DATE, 'DD/MM/YYYY')
AND TXDATE <= TO_DATE (T_DATE, 'DD/MM/YYYY')
)TL , SBSECURITIES SB,AFMAST AF ,CFMAST CF
WHERE OD.CODEID=SB.CODEID
AND TL.TXDATE = OD.TXDATE
AND TL.TXNUM=OD.TXNUM
AND OD.CIACCTNO=AF.ACCTNO
AND AF.CUSTID=CF.CUSTID
AND SB.SYMBOL LIKE V_STRSYMBOL
AND OD.EXECTYPE LIKE V_STREXECTYPE
--THANHTC THEM THAM SO PRICETYPE
AND OD.PRICETYPE LIKE V_STRPRICETYPE
--THANHTC END.
AND SB.TRADEPLACE LIKE V_STRTRADEPLACE
and od.VOUCHER like V_STRVOUCHER
)T
LEFT JOIN
( SELECT * FROM IOD
UNION ALL
SELECT * FROM IODHIST
) IO
ON IO.ORGORDERID=T.ORDERID
WHERE T.TYORDER LIKE V_STRTYPEORDER
ORDER BY T.CIACCTNO, T.TXDATE , T.ORDERID
;
*/
EXCEPTION
WHEN OTHERS
THEN
RETURN;
END; -- PROCEDURE
/
| true |
fa234736162bda4d38574c6a9c7cb92c9e0b10f5 | SQL | PR02-Rutenio/Proyecto | /sql/bbdd_rutenio.sql | UTF-8 | 4,913 | 3.28125 | 3 | [] | no_license | SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
CREATE DATABASE bbdd_rutenio;
-- CREATE USER 'admin'@'%' IDENTIFIED VIA mysql_native_password USING '***';GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 9999 MAX_CONNECTIONS_PER_HOUR 9999 MAX_UPDATES_PER_HOUR 9999 MAX_USER_CONNECTIONS 9997;GRANT ALL PRIVILEGES ON `admin\_%`.* TO 'admin'@'%';GRANT ALL PRIVILEGES ON `bbdd_rutenio`.* TO 'admin'@'%';
-- CREATE USER 'rutenio'@'%' IDENTIFIED VIA mysql_native_password USING '***';GRANT ALL PRIVILEGES ON *.* TO 'rutenio'@'%' REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 999 MAX_CONNECTIONS_PER_HOUR 999 MAX_UPDATES_PER_HOUR 999 MAX_USER_CONNECTIONS 999;CREATE DATABASE IF NOT EXISTS `rutenio`;GRANT ALL PRIVILEGES ON `rutenio`.* TO 'rutenio'@'%';GRANT ALL PRIVILEGES ON `rutenio\_%`.* TO 'rutenio'@'%';GRANT ALL PRIVILEGES ON `bbdd_rutenio`.* TO 'rutenio'@'%';
CREATE TABLE `recurso` (
`rec_id` int(4) NOT NULL,
`rec_tipo` varchar (25) COLLATE utf8_spanish_ci NOT NULL,
`rec_nombre` varchar (50) COLLATE utf8_spanish_ci NOT NULL,
`rec_disponibilidad` boolean NOT NULL,
`rec_fecha` timestamp NULL,
`rec_descripcion` text COLLATE utf8_spanish_ci NULL,
`rec_img` varchar(25) NULL,
`rec_incidencia` text COLLATE utf8_spanish_ci NULL,
`rec_incidencia_estado` boolean NOT NULL,
`rec_usado` int (4) NOT NULL,
`usu_id` int (4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
CREATE TABLE `usuario` (
`usu_id` int(4) NOT NULL,
`usu_nombre` varchar(50) COLLATE utf8_spanish_ci NOT NULL,
`usu_apellido` varchar(50) COLLATE utf8_spanish_ci NOT NULL,
`usu_correo` varchar(50) COLLATE utf8_spanish_ci NOT NULL,
`usu_password` varchar(50) COLLATE utf8_spanish_ci NOT NULL,
`usu_seguridad` varchar(30) COLLATE utf8_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
INSERT INTO `usuario` (`usu_id`, `usu_nombre`, `usu_apellido`, `usu_correo`, `usu_password`, `usu_seguridad`) VALUES
(1, 'Alex', 'Perez', 'alex@gmail.com', 'qweQWE123', 'Milú'),
(2, 'Irene', 'Fernandez', 'irene@gmail.com', 'asdASD123', 'Draco'),
(3, 'David', 'Gomez', 'david@gmail.com', 'zxcZXC123', 'Pitus'),
(4, 'Maria', 'Gil', 'maria@gmail.com', 'qazQAZ123', 'Akira'),
(5, 'Javier', 'Ortiz', 'javier@gmail.com', 'wsxWSX123', 'Flash'),
(6, 'Sherlock', 'Holmes', 'sherlock@gmail.com', 'abcABC123', 'Rocky'),
(7, 'John', 'Watson', 'john@gmail.com', '123456789', 'Bilbo'),
(8, 'Irene', 'Adler', 'adler@gmail.com', '987654321', 'Isti'),
(9, 'Admin', 'Admin', 'admin@gmail.com', '1234', 'Lumi');
INSERT INTO `recurso` (`rec_id`, `rec_tipo`, `rec_nombre`, `rec_disponibilidad`, `rec_fecha`, `rec_descripcion`, `rec_img`, `rec_incidencia`, `rec_incidencia_estado`, `rec_usado`, `usu_id`) VALUES
(1, 'Aula de teoría', 'Aula de teoría con proyector', '1', '2017-11-10 14:10:48', '', 'teoria_pry.png', '', '0', 2, 9),
(2, 'Aula de teoría', 'Aula de teoría con proyector', '1', '2017-11-10 14:10:48', '', 'teoria_pry.png', '', '0', 6, 9),
(3, 'Aula de teoría', 'Aula de teoría sin proyector', '1', '2017-11-10 14:10:48', '', 'teoria.png', '', '0', 3, 9),
(4, 'Aula de informática', 'Aula de informática', '1', '2017-11-10 14:10:48', '', 'informatica.png', '', '0', 9, 9),
(5, 'Aula de informática', 'Aula de informática', '1', '2017-11-10 14:10:48', '', 'informatica.png', '', '0', 5, 9),
(6, 'Sala', 'Despacho para entrevistas', '1', '2017-11-10 14:10:48', '', 'despacho.png', '', '0', 16, 9),
(7, 'Sala', 'Despacho para entrevistas', '1', '2017-11-10 14:10:48', '', 'despacho.png', '', '0', 15, 9),
(8, 'Sala', 'Sala de reuniones', '1', '2017-11-10 14:10:48', '', 'reuniones.png', '', '0', 0, 9),
(9, 'Proyector', 'Proyector', '1', '2017-11-10 14:10:48', '', 'proyector.png', '', '0', 13, 9),
(10, 'Carro de portatiles', 'Carro de portatiles', '1', '2017-11-10 14:10:48', '', 'carro.png', '', '0', 0, 9),
(11, 'Portátil', 'Portátil', '1', '2017-11-10 14:10:48', '', 'portatil.png', '', '0', 1, 9),
(12, 'Portátil', 'Portátil', '1', '2017-11-10 14:10:48', '', 'portatil.png', '', '0', 27, 9),
(13, 'Portátil', 'Portátil', '1', '2017-11-10 14:10:48', '', 'portatil.png', '', '0', 7, 9),
(14, 'Móvil', 'Móvil', '1', '2017-11-10 14:10:48', '', 'smartphone.png', '', '0', 0, 9),
(15, 'Móvil', 'Móvil', '1', '2017-11-10 14:10:48', '', 'smartphone.png', '', '0', 4, 9);
ALTER TABLE `recurso`
ADD PRIMARY KEY (`rec_id`);
ALTER TABLE `usuario`
ADD PRIMARY KEY (`usu_id`);
ALTER TABLE `recurso`
MODIFY `rec_id` int(4) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;
COMMIT;
ALTER TABLE `usuario`
MODIFY `usu_id` int(4) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;
COMMIT;
ALTER TABLE `recurso`
ADD CONSTRAINT `fk_recurso_usuario` FOREIGN KEY (`usu_id`) REFERENCES `usuario`(`usu_id`);
UPDATE `recurso` SET `usu_id` = '9' WHERE `rec_disponibilidad` = '1'; | true |
cf349a0a50eb95bc718c8393177b8452da5a10db | SQL | mylavarapuakhila/toll_fee_payment | /home/toll.sql | UTF-8 | 3,210 | 3.640625 | 4 | [
"CC-BY-3.0",
"CC-BY-4.0"
] | permissive | SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
CREATE TABLE `from` (
`city_id` int(10) UNSIGNED NOT NULL,
`city_name` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `city`
--
INSERT INTO `from` (`city_id`, `city_name`) VALUES
(1, 'Banglore'),
(2, 'Hyderabad'),
(3, 'Chennai');
CREATE TABLE `to` (
`city_id` int(10) UNSIGNED NOT NULL,
`city_name` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `city`
--
INSERT INTO `to` (`city_id`, `city_name`) VALUES
(1, 'Banglore'),
(2, 'Hyderabad'),
(3, 'Chennai');
CREATE TABLE `way` (
`way_id` int(10) UNSIGNED NOT NULL,
`way_name` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `city`
--
INSERT INTO `way` (`way_id`, `way_name`) VALUES
(1, '1 way'),
(2, '2 way');
CREATE TABLE `vehicle_type` (
`vehicle_id` int(10) UNSIGNED NOT NULL,
`vehicle_name` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `city`
--
INSERT INTO `vehicle_type` (`vehicle_id`, `vehicle_name`) VALUES
(1, 'car/jeep'),
(2, 'lorry/truck'),
(3, 'bus');
CREATE TABLE `register` (
`register_id` int(11) NOT NULL,
`register_first` varchar(255) NOT NULL,
`register_last` varchar(255) NOT NULL,
`register_email` varchar(255) NOT NULL,
`register_mobile` varchar(255) NOT NULL,
`registe_password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
--
-- Dumping data for table `customer`
--
CREATE TABLE `tolls` (
`tolls_id` int(10) UNSIGNED NOT NULL,
`tolls_name` varchar(45) NOT NULL,
`tolls_from` varchar(45) NOT NULL,
`tolls_to` varchar(45) NOT NULL,
`tolls_price` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `city`
--
ALTER TABLE `from`
ADD PRIMARY KEY (`city_id`);
--
-- Indexes for table `country`
--
ALTER TABLE `to`
ADD PRIMARY KEY (`city_id`);
--
-- Indexes for table `customer`
--
ALTER TABLE `way`
ADD PRIMARY KEY (`way_id`);
--
-- Indexes for table `department`
--
ALTER TABLE `vehicle_type`
ADD PRIMARY KEY (`vehicle_id`);
--
-- Indexes for table `employee`
--
ALTER TABLE `register`
ADD PRIMARY KEY (`register_id`);
--
-- Indexes for table `login`
--
ALTER TABLE `tolls`
ADD PRIMARY KEY (`tolls_id`);
ALTER TABLE `from`
MODIFY `city_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `country`
--
ALTER TABLE `to`
MODIFY `city_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `customer`
--
ALTER TABLE `way`
MODIFY `way_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `department`
--
ALTER TABLE `vehicle_type`
MODIFY `vehicle_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `employee`
--
ALTER TABLE `register`
MODIFY `register_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
--
-- AUTO_INCREMENT for table `login`
--
ALTER TABLE `tolls`
MODIFY `tolls_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
| true |
aa353a2003d531382523adaa629c700bef575c3d | SQL | VinceOmega/tsql_AgentStudio | /GetAllSitesWithExpirationDatesOlderThan6DaysFromCurrentDateWithJoinsUsedInBillingLoop.sql | UTF-8 | 1,997 | 3.5 | 4 | [] | no_license | SELECT TOP 1000 site.IsDelinquent, site.InvoiceablePackage, site.InvoiceableAddons, site.AppGUID, site.AppId, site.SiteName, site.ExpirationDate, site.AuthNetProfileID, site.IsActive, site.CanExpire, site.PackageId, site.InTrial, site.CreatedDate,
defaultalias.DomainName AS DefaultDomain,
primaryalias.DomainName AS PrimaryDomain,
SiteOwner.Username, SiteOwner.Firstname, SiteOwner.LastName, SiteOwner.AppUrl,
frequency.Id AS FrequencyId, frequency.Name AS SubscriptionName, frequency.LengthInMonths AS SubscriptionPeriod,
package.IsFree,
promocode.Id AS PromoId, promocode.Code AS PromoCode, promocode.Guid AS PromoGuid,
partner.Id AS PartnerId, partner.Name AS PartnerName, partner.IsReseller, partner.IsEnterprise
FROM AgentStudio.dbo.sites AS site
INNER JOIN AgentStudio.dbo.site_aliases AS defaultalias ON defaultalias.AppGuid = site.AppGUID
INNER JOIN AgentStudio.dbo.site_aliases AS primaryalias ON primaryalias.AppGuid = site.AppGUID
INNER JOIN Travalliance_Container.Travalliance.RemoteAccess.SiteOwners AS SiteOwner ON SiteOwner.AppGUID = site.AppGUID
INNER JOIN AgentStudio.Common.Frequencies AS frequency ON frequency.Id = site.FrequencyId
INNER JOIN AgentStudio.dbo.Packages AS package ON package.Id = site.PackageId
INNER JOIN AgentStudio.dbo.site_promo_codes AS sitepromocode ON sitepromocode.AppGuid = site.AppGUID
INNER JOIN AgentStudio.Common.PromoCodes AS promocode ON promocode.GUID = sitepromocode.PromoCodeGUID
INNER JOIN AgentStudio.Marketing.Partners AS partner ON partner.Id = promocode.PartnerId
WHERE site.CanExpire = 0
AND site.IsCancelled = 0
AND site.IsDeleted = 0
AND site.IsDeveloperSite = 0
AND site.IsTestSite = 0
AND site.InTrial = 0
AND site.IsActive = 1
AND defaultalias.IsDefault = 1
AND primaryalias.IsPrimary = 1
AND sitepromocode.IsCurrent = 1
AND site.ExpirationDate < DATEADD( day, -6, GETDATE() )
ORDER BY PackageId DESC | true |
a3ca4698265ad75297884ad08b6dd3435a7ae320 | SQL | alberto-guzman/sql_hw_notebooks | /hw03_GuzmanAlvarez_Alberto_stocks_db_create_queries.sql | UTF-8 | 1,829 | 4.46875 | 4 | [] | no_license | -- create a database for tb data
CREATE DATABASE stock_db;
USE stock_db;
-- create a table for company_info
CREATE TABLE company_info (
company_id int NOT NULL,
company text NOT NULL,
symbol text,
sector text,
PRIMARY KEY (company_id)
);
-- import data
-- create table for exchange_info
CREATE TABLE exchange_info (
exchange_id int NOT NULL,
exchange text NOT NULL,
PRIMARY KEY (exchange_id)
);
-- import data
-- create table for tb_per_year
CREATE TABLE stock_per_day (
id int NOT NULL AUTO_INCREMENT,
company_id int NOT NULL,
exchange_id int NOT NULL,
date text,
close int,
high int,
open int,
year int,
month int,
day int,
wday int,
quarter int,
o_c_diff int,
PRIMARY KEY (id),
FOREIGN KEY (company_id) REFERENCES company_info(company_id),
FOREIGN KEY (exchange_id) REFERENCES exchange_info(exchange_id)
);
-- import data
-- QUERIES
-- Query the close price for Tesla for all trading days.
SELECT close, company
FROM stock_per_day
LEFT JOIN company_info USING (company_id)
LEFT JOIN exchange_info USING (exchange_id)
WHERE symbol = 'TSLA';
-- Query the low and high prices for Gamestop for all trading days.
SELECT
MAX(close) AS 'High Price'
, MIN(close) AS 'Low Price'
FROM stock_per_day
LEFT JOIN company_info USING (company_id)
LEFT JOIN exchange_info USING (exchange_id)
WHERE symbol = 'GME';
-- Query the maximum close price for all companies.
SELECT company,
MAX(close) AS 'Max Close Price'
FROM stock_per_day
LEFT JOIN company_info USING (company_id)
LEFT JOIN exchange_info USING (exchange_id)
GROUP BY company;
-- Query the average close price for all companies in each month.
SELECT company, month,
AVG(close) AS 'Average Close Price'
FROM stock_per_day
LEFT JOIN company_info USING (company_id)
LEFT JOIN exchange_info USING (exchange_id)
GROUP BY company, month
ORDER BY company, month; | true |
7a4604d86bbd312b7bc712abd90ad1f3e23b8556 | SQL | Scorcherfjk/CSI-clients | /querys.sql | UTF-8 | 3,788 | 3.734375 | 4 | [
"Unlicense"
] | permissive | select fecha.registro,
cliente.nombre,
responsable.nombre,
proyecto.oportunidad,
contacto.nombre,
contacto.apellido
from fecha, cliente, responsable, proyecto, contacto
where fecha.proyecto_idproyecto = proyecto.idproyecto
AND fecha.contacto_idcontacto = contacto.idcontacto
AND fecha.responsable_idresponsable = responsable.idresponsable
AND contacto.cliente_idcliente = cliente.idcliente
order by proyecto.idproyecto
/******************funciona**********************/
select fecha.registro, proyecto.oportunidad
from fecha, proyecto
where fecha.proyecto_idproyecto = proyecto.idproyecto
/******************funciona**********************/
select fecha.registro, proyecto.oportunidad, contacto.nombre
from fecha, proyecto, contacto
where fecha.proyecto_idproyecto = proyecto.idproyecto
AND fecha.contacto_idcontacto = contacto.idcontacto
/******************funciona**********************/
select fecha.registro, responsable.nombre, proyecto.oportunidad, contacto.nombre
from fecha, responsable, proyecto, contacto
where fecha.proyecto_idproyecto = proyecto.idproyecto
AND fecha.contacto_idcontacto = contacto.idcontacto
AND fecha.responsable_idresponsable = responsable.idresponsable
/******************funciona**********************/
select fecha.registro, cliente.nombre, responsable.nombre, proyecto.oportunidad, contacto.nombre
from fecha, cliente, responsable, proyecto, contacto
where fecha.proyecto_idproyecto = proyecto.idproyecto
AND fecha.contacto_idcontacto = contacto.idcontacto
AND fecha.responsable_idresponsable = responsable.idresponsable
AND contacto.cliente_idcliente = cliente.idcliente
/******************funciona**********************/
select fecha.registro, cliente.nombre, responsable.nombre, proyecto.oportunidad, contacto.nombre
from fecha, cliente, responsable, proyecto, contacto
where fecha.proyecto_idproyecto = proyecto.idproyecto
AND fecha.contacto_idcontacto = contacto.idcontacto
AND fecha.responsable_idresponsable = responsable.idresponsable
AND contacto.cliente_idcliente = cliente.idcliente
order by proyecto.idproyecto
/******************funciona**********************/
select fecha.registro,
cliente.nombre,
responsable.nombre,
proyecto.oportunidad,
contacto.nombre,
contacto.apellido,
fecha.aceptacion,
concat(fecha.oferta - curdate(), " dias restantes") AS estado
from fecha, cliente, responsable, proyecto, contacto
where fecha.proyecto_idproyecto = proyecto.idproyecto
AND fecha.contacto_idcontacto = contacto.idcontacto
AND fecha.responsable_idresponsable = responsable.idresponsable
AND contacto.cliente_idcliente = cliente.idcliente
AND fecha.oferta - curdate() > -1
order by proyecto.idproyecto
/******************funciona**********************/
SELECT fecha.registro as registro ,
cliente.nombre as cliente ,
responsable.iniciales as iniciales,
proyecto.oportunidad as oportunidad ,
contacto.nombre as cnombre ,
contacto.apellido as capellido ,
fecha.aceptacion as aceptacion ,
fecha.visita as visita ,
fecha.consultas as consultas ,
fecha.respuestas as respuestas ,
fecha.oferta as oferta ,
fecha.decision as decision ,
proyecto.enviado as enviado ,
proyecto.cotizacion as cotizacion ,
concat(fecha.oferta - curdate(), ' dias restantes') as estado,
proyecto.comentario as comentario
FROM fecha, cliente, responsable, proyecto, contacto
WHERE fecha.proyecto_idproyecto = proyecto.idproyecto
AND fecha.contacto_idcontacto = contacto.idcontacto
AND fecha.responsable_idresponsable = responsable.idresponsable
AND contacto.cliente_idcliente = cliente.idcliente
ORDER BY proyecto.idproyecto | true |
c692c55549494aeb296b20c91a420cc0d791b64b | SQL | mdevaux001/ProjetWeb | /sql/quest.sql | UTF-8 | 6,768 | 3.203125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Hôte : 127.0.0.1
-- Généré le : lun. 05 mars 2018 à 17:10
-- Version du serveur : 10.1.30-MariaDB
-- Version de PHP : 7.2.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `quest`
--
-- --------------------------------------------------------
--
-- Structure de la table `campagne`
--
CREATE TABLE `campagne` (
`camp_id` int(10) NOT NULL,
`camp_nom` varchar(100) NOT NULL,
`camp_desc` varchar(1000) DEFAULT NULL,
`camp_deb` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`camp_fin` datetime DEFAULT NULL,
`camp_exr` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `contient`
--
CREATE TABLE `contient` (
`qutaire` int(10) NOT NULL,
`quest` int(10) NOT NULL,
`qutaire_type` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `experience`
--
CREATE TABLE `experience` (
`exr_id` int(10) NOT NULL,
`exr_nom` varchar(100) NOT NULL,
`exr_desc` varchar(1000) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `experiment`
--
CREATE TABLE `experiment` (
`exp_id` int(10) NOT NULL,
`exp_mdp` varchar(50) NOT NULL,
`exp_nom` varchar(100) NOT NULL,
`exp_prenom` varchar(100) NOT NULL,
`exp_org` varchar(100) DEFAULT NULL,
`exp_mail` varchar(100) NOT NULL,
`exp_img` varchar(100) NOT NULL DEFAULT 'defaut.png'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `lancer`
--
CREATE TABLE `lancer` (
`exp` int(10) NOT NULL,
`exr` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `questaire`
--
CREATE TABLE `questaire` (
`qutaire_id` int(10) NOT NULL,
`qutaire_camp` int(10) NOT NULL,
`qutaire_titre` varchar(100) NOT NULL,
`qutaire_desc` varchar(2000) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `question`
--
CREATE TABLE `question` (
`quest_id` int(10) NOT NULL,
`quest_type` varchar(50) NOT NULL,
`quest_ech` int(3) NOT NULL,
`quest_text` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `reponse`
--
CREATE TABLE `reponse` (
`usr` int(10) NOT NULL,
`qutaire` int(10) NOT NULL,
`quest` int(10) NOT NULL,
`valeur` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `user`
--
CREATE TABLE `user` (
`usr_id` int(10) NOT NULL,
`usr_mdp` varchar(100) NOT NULL,
`usr_mail` varchar(100) NOT NULL,
`usr_org` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `campagne`
--
ALTER TABLE `campagne`
ADD PRIMARY KEY (`camp_id`),
ADD KEY `camp_exr` (`camp_exr`);
--
-- Index pour la table `contient`
--
ALTER TABLE `contient`
ADD PRIMARY KEY (`qutaire`,`quest`),
ADD KEY `quest` (`quest`);
--
-- Index pour la table `experience`
--
ALTER TABLE `experience`
ADD PRIMARY KEY (`exr_id`);
--
-- Index pour la table `experiment`
--
ALTER TABLE `experiment`
ADD PRIMARY KEY (`exp_id`);
--
-- Index pour la table `lancer`
--
ALTER TABLE `lancer`
ADD PRIMARY KEY (`exp`,`exr`),
ADD KEY `exr` (`exr`);
--
-- Index pour la table `questaire`
--
ALTER TABLE `questaire`
ADD PRIMARY KEY (`qutaire_id`),
ADD KEY `qutaire_camp` (`qutaire_camp`);
--
-- Index pour la table `question`
--
ALTER TABLE `question`
ADD PRIMARY KEY (`quest_id`);
--
-- Index pour la table `reponse`
--
ALTER TABLE `reponse`
ADD PRIMARY KEY (`usr`,`qutaire`,`quest`),
ADD KEY `qutaire` (`qutaire`),
ADD KEY `quest` (`quest`);
--
-- Index pour la table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`usr_id`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `campagne`
--
ALTER TABLE `campagne`
MODIFY `camp_id` int(10) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `experience`
--
ALTER TABLE `experience`
MODIFY `exr_id` int(10) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `experiment`
--
ALTER TABLE `experiment`
MODIFY `exp_id` int(10) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `questaire`
--
ALTER TABLE `questaire`
MODIFY `qutaire_id` int(10) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `question`
--
ALTER TABLE `question`
MODIFY `quest_id` int(10) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `user`
--
ALTER TABLE `user`
MODIFY `usr_id` int(10) NOT NULL AUTO_INCREMENT;
--
-- Contraintes pour les tables déchargées
--
--
-- Contraintes pour la table `campagne`
--
ALTER TABLE `campagne`
ADD CONSTRAINT `campagne_ibfk_1` FOREIGN KEY (`camp_exr`) REFERENCES `experience` (`exr_id`);
--
-- Contraintes pour la table `contient`
--
ALTER TABLE `contient`
ADD CONSTRAINT `contient_ibfk_1` FOREIGN KEY (`qutaire`) REFERENCES `questaire` (`qutaire_id`),
ADD CONSTRAINT `contient_ibfk_2` FOREIGN KEY (`quest`) REFERENCES `question` (`quest_id`);
--
-- Contraintes pour la table `lancer`
--
ALTER TABLE `lancer`
ADD CONSTRAINT `lancer_ibfk_1` FOREIGN KEY (`exp`) REFERENCES `experiment` (`exp_id`),
ADD CONSTRAINT `lancer_ibfk_2` FOREIGN KEY (`exr`) REFERENCES `experience` (`exr_id`);
--
-- Contraintes pour la table `questaire`
--
ALTER TABLE `questaire`
ADD CONSTRAINT `questaire_ibfk_1` FOREIGN KEY (`qutaire_camp`) REFERENCES `campagne` (`camp_id`);
--
-- Contraintes pour la table `reponse`
--
ALTER TABLE `reponse`
ADD CONSTRAINT `reponse_ibfk_1` FOREIGN KEY (`usr`) REFERENCES `user` (`usr_id`),
ADD CONSTRAINT `reponse_ibfk_2` FOREIGN KEY (`qutaire`) REFERENCES `questaire` (`qutaire_id`),
ADD CONSTRAINT `reponse_ibfk_3` FOREIGN KEY (`quest`) REFERENCES `question` (`quest_id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
62e9dff0d9ab4ba74bfad54f3fcdf42443463f0d | SQL | AbabiyaAbajo/AntiCorruptionProject | /database/acsite.sql | UTF-8 | 20,983 | 3.125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 12, 2019 at 10:33 PM
-- Server version: 10.4.6-MariaDB
-- PHP Version: 7.3.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `acsite`
--
-- --------------------------------------------------------
--
-- Table structure for table `assigned_quizzes`
--
CREATE TABLE `assigned_quizzes` (
`id` int(11) NOT NULL,
`quiz_id` int(11) NOT NULL,
`assignee_id` int(11) NOT NULL,
`submitted` int(1) NOT NULL DEFAULT 0,
`assigned_on` timestamp NOT NULL DEFAULT current_timestamp(),
`submitted_on` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
--
-- Dumping data for table `assigned_quizzes`
--
INSERT INTO `assigned_quizzes` (`id`, `quiz_id`, `assignee_id`, `submitted`, `assigned_on`, `submitted_on`) VALUES
(1, 14, 11, 1, '2019-11-19 19:16:50', '2019-11-19 19:18:53'),
(2, 32, 8, 0, '2019-12-01 05:00:00', '0000-00-00 00:00:00'),
(3, 32, 5, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(4, 32, 10, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(5, 32, 3, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(6, 33, 10, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(7, 33, 2, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(8, 32, 8, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
(9, 1, 8, 0, '0000-00-00 00:00:00', '0000-00-00 00:00:00');
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`name` varchar(100) COLLATE utf8mb4_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `name`) VALUES
(1, 'Code of conduct'),
(2, 'Policy and Procedures'),
(3, 'Confidential reporting (whistle blowing)'),
(4, 'Internal investigation'),
(5, 'Internal controls'),
(6, 'Leadership and governance'),
(7, 'M&A, Joint venture & business associate due diligence'),
(8, 'Program testing and benchmarking'),
(9, 'Risk assessments'),
(10, 'Structuring an ethics, anti-corruption and compliance program'),
(11, 'Third party due diligence'),
(12, 'Conflict of interest'),
(13, 'Ethics and compliance red flags'),
(14, 'Preventing ethics, anti-corruption and other compliance failures'),
(15, 'Doing the right thing when facing ethical challenges'),
(16, 'Improving the organizational culture'),
(17, 'Business case for ethics & compliance'),
(18, 'Legal case for ethics and compliance');
-- --------------------------------------------------------
--
-- Table structure for table `censoredwords`
--
CREATE TABLE `censoredwords` (
`id` int(11) NOT NULL,
`word` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `censoredwords`
--
INSERT INTO `censoredwords` (`id`, `word`) VALUES
(1, 'fuck'),
(2, 'bitch');
-- --------------------------------------------------------
--
-- Table structure for table `industries`
--
CREATE TABLE `industries` (
`id` int(11) NOT NULL,
`name` varchar(100) COLLATE utf8mb4_bin NOT NULL,
`active` int(1) NOT NULL DEFAULT 0,
`submitted_by` int(11) NOT NULL,
`submitted_on` timestamp NOT NULL DEFAULT current_timestamp(),
`approved_by` int(11) NOT NULL,
`approved_on` timestamp NULL DEFAULT NULL ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
--
-- Dumping data for table `industries`
--
INSERT INTO `industries` (`id`, `name`, `active`, `submitted_by`, `submitted_on`, `approved_by`, `approved_on`) VALUES
(1, 'Agriculture', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:26:50'),
(2, 'Arms, defense & military', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:20'),
(3, 'Banking & finance', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:22'),
(4, 'Civilian aerospace', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:28'),
(5, 'Consumer services', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:30'),
(6, 'Fisheries', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:32'),
(7, 'Forestry', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:33'),
(8, 'Heavy manufacturing', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:34'),
(9, 'Information technology', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:36'),
(10, 'Light manufacturing', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:19'),
(11, 'Oil and gas', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:18'),
(12, 'Pharmaceutical & health care', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:26:56'),
(13, 'Power generation & transmission', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:08'),
(14, 'Public works & Construction', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:09'),
(15, 'Real estate, property, legal and business services', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:11'),
(16, 'Telecommunications', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:12'),
(17, 'Transportation & storage', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:14'),
(18, 'Utilities', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:15'),
(19, 'Public services', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:16'),
(20, 'Other', 1, 11, '2019-11-25 06:08:05', 11, '2019-11-25 06:27:37');
-- --------------------------------------------------------
--
-- Table structure for table `questions`
--
CREATE TABLE `questions` (
`id` int(16) NOT NULL,
`userid` int(16) UNSIGNED NOT NULL,
`question` varchar(500) NOT NULL,
`answer_1` varchar(500) NOT NULL,
`answer_2` varchar(500) NOT NULL,
`answer_3` varchar(500) DEFAULT NULL,
`answer_4` varchar(500) DEFAULT NULL,
`answer` int(11) NOT NULL,
`type` int(11) NOT NULL,
`date_created` date NOT NULL,
`link` varchar(500) DEFAULT NULL,
`ticketid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `questions`
--
INSERT INTO `questions` (`id`, `userid`, `question`, `answer_1`, `answer_2`, `answer_3`, `answer_4`, `answer`, `type`, `date_created`, `link`, `ticketid`) VALUES
(14, 7, 'agile is ', 'fun', 'useful', 'very fun', 'not fun', 3, 1, '2019-04-15', NULL, 2),
(16, 7, 'What is APIPA?', 'option 1', 'option 2', 'option 3', 'option 4', 2, 1, '2019-10-30', NULL, 2),
(17, 7, 'What is AWS?', 'Google\'s web services?', 'Amazon\'s web services?', 'Microsoft\'s web services?', 'idk', 2, 1, '2019-11-04', NULL, 2),
(18, 12, 'If you see corruption you should..', 'Get out of there', 'Speak up', 'Pretend you saw nothing', 'None of the above', 2, 1, '2019-12-03', NULL, 2),
(19, 12, 'Would you pay a small amount to a driving instructor to pass a test?', 'If you had to', 'Without hesitation', 'Never', 'Maybe', 3, 1, '2019-12-03', NULL, 2),
(20, 12, 'Bribing people is ok', 'True', 'False', NULL, NULL, 2, 2, '2019-12-03', NULL, 2),
(21, 12, 'Paying a police officer a small amount to escape a larger fine is acceptable', 'True', 'False', NULL, NULL, 2, 2, '2019-12-03', NULL, 2),
(22, 12, 'In business, it\'s \"you scratch my back, and I\'ll scratch yours.\"', 'True', 'False', NULL, NULL, 2, 2, '2019-12-03', NULL, 2),
(23, 12, 'You should avoid giving a job to a relative if they were under-qualified for the position.', 'True', 'False', NULL, NULL, 1, 2, '2019-12-03', NULL, 2);
-- --------------------------------------------------------
--
-- Table structure for table `quizzes`
--
CREATE TABLE `quizzes` (
`id` int(16) UNSIGNED NOT NULL,
`title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`userid` int(16) UNSIGNED NOT NULL,
`description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`industry_id` int(11) NOT NULL,
`tag_one` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT 'NULL',
`tag_two` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT 'NULL',
`tag_three` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT 'NULL',
`created` timestamp NOT NULL DEFAULT current_timestamp(),
`edited_on` timestamp NULL DEFAULT NULL ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `quizzes`
--
INSERT INTO `quizzes` (`id`, `title`, `userid`, `description`, `industry_id`, `tag_one`, `tag_two`, `tag_three`, `created`, `edited_on`) VALUES
(1, 'test', 8, 'test', 1, NULL, NULL, NULL, '2019-04-15 04:00:00', '2019-11-24 19:38:43'),
(2, 'wef', 7, 'sdfsdf', 2, NULL, NULL, NULL, '2019-04-15 04:00:00', '2019-11-24 19:38:46'),
(3, 'leanne', 7, 'test quiz', 3, NULL, NULL, NULL, '2019-04-15 04:00:00', '2019-11-24 19:38:49'),
(4, 'This is Ilya\'s quiz', 7, 'test', 4, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:38:52'),
(5, 'This is Ilya\'s quiz', 7, 'test', 5, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:38:54'),
(6, 'This is Ilya\'s quiz', 7, 'zcxz', 6, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:38:56'),
(7, 'werwsrw', 7, 'wer', 2, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:38:59'),
(8, 'dfgd', 7, 'dgfg', 3, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:39:02'),
(9, 'sfdff', 7, 'sdf', 8, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:39:04'),
(10, 'sfdff', 7, 'sdf', 1, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:39:07'),
(11, 'wqeq', 7, 'qwe', 2, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:39:10'),
(12, 'zxc', 7, 'zxc', 3, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:39:14'),
(13, '1234', 7, 'zxc', 4, NULL, NULL, NULL, '2019-11-02 04:00:00', '2019-11-24 19:39:17'),
(32, 'this is new quiz', 11, '123', 5, 'NULL', 'NULL', 'NULL', '2019-11-23 17:08:31', '2019-11-24 19:39:20'),
(33, 'q', 11, 'qwe', 0, 'NULL', 'NULL', 'NULL', '2019-11-24 23:04:31', '0000-00-00 00:00:00'),
(34, 'asdasd', 11, 'asd', 0, 'NULL', 'NULL', 'NULL', '2019-11-24 23:14:33', '0000-00-00 00:00:00'),
(35, 'rtre', 11, 'gretg', 0, 'NULL', 'NULL', 'NULL', '2019-11-24 23:16:12', '0000-00-00 00:00:00'),
(36, 'this is 24324', 11, '234234', 0, 'NULL', 'NULL', 'NULL', '2019-11-24 23:21:24', '0000-00-00 00:00:00'),
(37, 'asd', 11, 'asd', 0, 'NULL', 'NULL', 'NULL', '2019-11-24 23:22:47', '0000-00-00 00:00:00'),
(38, 'asdasd', 11, 'asd', 0, 'NULL', 'NULL', 'NULL', '2019-11-24 23:28:24', '0000-00-00 00:00:00'),
(39, 'zzzz', 11, 'zzzz', 14, 'NULL', 'NULL', 'NULL', '2019-11-24 23:33:50', '0000-00-00 00:00:00'),
(40, '1111', 11, '123123', 20, 'NULL', 'NULL', 'NULL', '2019-11-24 23:36:36', '0000-00-00 00:00:00'),
(41, 'wer', 11, '', 2, 'NULL', 'NULL', 'NULL', '2019-11-25 00:22:51', '0000-00-00 00:00:00'),
(42, 'saa', 11, NULL, 2, 'NULL', 'NULL', 'NULL', '2019-11-25 00:27:42', '0000-00-00 00:00:00'),
(43, 'qqq', 11, 'qq', 1, 'NULL', 'NULL', 'NULL', '2019-11-25 04:20:22', '0000-00-00 00:00:00'),
(44, 'asdasd', 11, 'qqq', 16, 'NULL', 'NULL', 'NULL', '2019-11-25 04:20:51', '0000-00-00 00:00:00'),
(45, 'rer', 11, NULL, 0, 'NULL', 'NULL', 'NULL', '2019-11-25 04:57:07', '0000-00-00 00:00:00'),
(46, 'sasdad', 11, NULL, 1, 'NULL', 'NULL', 'NULL', '2019-11-25 04:58:50', '0000-00-00 00:00:00'),
(47, 'This is test', 11, 'thsgsdf', 12, 'NULL', 'NULL', 'NULL', '2019-11-25 14:40:54', '0000-00-00 00:00:00'),
(48, 'Anti-money Laundering and Real Estate as a High Risk Sector', 12, NULL, 15, 'NULL', 'NULL', 'NULL', '2019-11-25 19:31:04', '0000-00-00 00:00:00'),
(49, 'Anti-corruption Checklist in National and International Business Transactions', 12, NULL, 3, 'NULL', 'NULL', 'NULL', '2019-11-25 19:31:47', '0000-00-00 00:00:00'),
(50, 'Preventing Bribery and Corruption Through Strong Controls, Policies and Procedures', 12, NULL, 20, 'NULL', 'NULL', 'NULL', '2019-11-25 19:32:10', '0000-00-00 00:00:00'),
(51, 'Internal Structures: How to Identify and Deal with Red Flags', 12, NULL, 20, 'NULL', 'NULL', 'NULL', '2019-11-25 19:33:01', '0000-00-00 00:00:00'),
(52, 'Accountability, Leadership and Responsibilities – What it Means and How to Own it', 12, NULL, 20, 'NULL', 'NULL', 'NULL', '2019-11-25 19:33:31', '0000-00-00 00:00:00'),
(53, 'zxc', 11, 'zxc', 6, 'NULL', 'NULL', 'NULL', '2019-12-02 14:02:44', '0000-00-00 00:00:00'),
(54, '123123', 11, NULL, 14, 'NULL', 'NULL', 'NULL', '2019-12-02 15:09:34', '0000-00-00 00:00:00'),
(56, 'testttt', 12, 'testttt', 1, 'NULL', 'NULL', 'NULL', '2019-12-03 13:40:08', '0000-00-00 00:00:00'),
(57, 'dfs', 12, NULL, 1, 'NULL', 'NULL', 'NULL', '2019-12-03 15:16:20', '0000-00-00 00:00:00'),
(58, 'This is test', 12, NULL, 3, 'NULL', 'NULL', 'NULL', '2019-12-03 15:38:49', '0000-00-00 00:00:00'),
(59, 'new', 12, NULL, 19, 'NULL', 'NULL', 'NULL', '2019-12-03 15:58:23', '0000-00-00 00:00:00'),
(60, 'xvxc', 12, NULL, 19, 'NULL', 'NULL', 'NULL', '2019-12-03 16:19:04', '0000-00-00 00:00:00'),
(61, 'IGdfgfd', 12, NULL, 13, 'NULL', 'NULL', 'NULL', '2019-12-03 16:22:57', '0000-00-00 00:00:00'),
(62, 'zxczc', 12, NULL, 14, 'NULL', 'NULL', 'NULL', '2019-12-03 16:44:17', '0000-00-00 00:00:00');
-- --------------------------------------------------------
--
-- Table structure for table `quizzes_questions`
--
CREATE TABLE `quizzes_questions` (
`quizid` int(16) UNSIGNED NOT NULL,
`questionid` int(16) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `quizzes_questions`
--
INSERT INTO `quizzes_questions` (`quizid`, `questionid`) VALUES
(3, 16),
(3, 17),
(48, 18),
(48, 19),
(48, 21),
(48, 23);
-- --------------------------------------------------------
--
-- Table structure for table `roles`
--
CREATE TABLE `roles` (
`id` int(16) NOT NULL,
`name` varchar(15) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `roles`
--
INSERT INTO `roles` (`id`, `name`) VALUES
(1, 'General'),
(2, 'Admin');
-- --------------------------------------------------------
--
-- Table structure for table `submitted_answers`
--
CREATE TABLE `submitted_answers` (
`id` int(11) NOT NULL,
`quiz_id` int(11) NOT NULL,
`question_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`answer` varchar(500) CHARACTER SET utf8 NOT NULL,
`submitted_on` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
--
-- Dumping data for table `submitted_answers`
--
INSERT INTO `submitted_answers` (`id`, `quiz_id`, `question_id`, `user_id`, `answer`, `submitted_on`) VALUES
(9, 3, 15, 7, 'False', '2019-11-04 15:22:37'),
(10, 3, 16, 7, 'option 4', '2019-11-04 15:22:38'),
(11, 3, 17, 7, 'idk', '2019-11-04 15:22:32'),
(12, 16, 1, 11, 'False', '2019-11-19 15:54:22'),
(13, 14, 1, 11, 'False', '2019-11-20 05:29:24'),
(14, 14, 3, 11, 'True', '2019-11-20 05:29:23'),
(15, 14, 2, 11, 'sdf', '2019-11-20 05:29:25'),
(16, 22, 1, 11, 'True', '2019-11-20 05:29:41'),
(17, 30, 17, 11, 'Google\'s web services?', '2019-11-23 00:00:58'),
(18, 32, 1, 11, 'True', '2019-12-02 15:13:26'),
(19, 32, 2, 11, 'sdf', '2019-12-02 15:13:28'),
(20, 48, 18, 12, 'Pretend you saw nothing', '2019-12-03 16:58:44'),
(21, 48, 19, 12, 'Without hesitation', '2019-12-03 16:24:28'),
(22, 48, 21, 12, 'True', '2019-12-03 16:24:29'),
(23, 48, 23, 12, 'True', '2019-12-03 16:24:30');
-- --------------------------------------------------------
--
-- Table structure for table `tickets`
--
CREATE TABLE `tickets` (
`id` int(11) NOT NULL,
`Name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `tickets`
--
INSERT INTO `tickets` (`id`, `Name`) VALUES
(1, 'Safe'),
(2, 'Censorship Issue'),
(3, 'No Ticket'),
(4, 'Admin Request');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(16) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`salt` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`roleid` int(11) NOT NULL,
`ticketid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `password`, `salt`, `roleid`, `ticketid`) VALUES
(2, 'kishan', 'k@k.com', '123123123', '', 1, 3),
(3, 'admin', 'admin@admin.com', '123123123', '', 2, 3),
(5, 'ilya admin', 'ilyaAdmin@yahoo.ca', '123', '', 2, 3),
(6, '123', '123@yahoo.ca', '123', '', 2, 3),
(7, 'Gedan', 'ilyak@yahoo.ca', 'zxc', '', 1, 4),
(8, 'zx', 'zxc@yahoo.ca', 'zxc', '', 1, 3),
(9, 'amd', 'amd@yahoo.ca', 'zxc', '', 1, 3),
(10, 'ilya', 'ilya@yahoo.ca', 'zxc', '', 1, 3),
(11, 'zxc', 'zxc@gmail.com', 'zxc', '', 1, 3),
(12, 'Kishan', 'kishan@gmail.com', 'zxc', '', 1, 3);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `assigned_quizzes`
--
ALTER TABLE `assigned_quizzes`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `censoredwords`
--
ALTER TABLE `censoredwords`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `industries`
--
ALTER TABLE `industries`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `questions`
--
ALTER TABLE `questions`
ADD PRIMARY KEY (`id`),
ADD KEY `userid` (`userid`),
ADD KEY `ticketid` (`ticketid`);
--
-- Indexes for table `quizzes`
--
ALTER TABLE `quizzes`
ADD PRIMARY KEY (`id`),
ADD KEY `userid` (`userid`);
--
-- Indexes for table `quizzes_questions`
--
ALTER TABLE `quizzes_questions`
ADD KEY `quizid` (`quizid`),
ADD KEY `questionid` (`questionid`);
--
-- Indexes for table `roles`
--
ALTER TABLE `roles`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `submitted_answers`
--
ALTER TABLE `submitted_answers`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tickets`
--
ALTER TABLE `tickets`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD KEY `roleid` (`roleid`),
ADD KEY `ticketid` (`ticketid`) USING BTREE;
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `assigned_quizzes`
--
ALTER TABLE `assigned_quizzes`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
--
-- AUTO_INCREMENT for table `censoredwords`
--
ALTER TABLE `censoredwords`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `industries`
--
ALTER TABLE `industries`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT for table `questions`
--
ALTER TABLE `questions`
MODIFY `id` int(16) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
--
-- AUTO_INCREMENT for table `quizzes`
--
ALTER TABLE `quizzes`
MODIFY `id` int(16) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=63;
--
-- AUTO_INCREMENT for table `roles`
--
ALTER TABLE `roles`
MODIFY `id` int(16) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `submitted_answers`
--
ALTER TABLE `submitted_answers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
--
-- AUTO_INCREMENT for table `tickets`
--
ALTER TABLE `tickets`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(16) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `questions`
--
ALTER TABLE `questions`
ADD CONSTRAINT `ticketid` FOREIGN KEY (`ticketid`) REFERENCES `tickets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `quizzes`
--
ALTER TABLE `quizzes`
ADD CONSTRAINT `quizzes_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `quizzes_questions`
--
ALTER TABLE `quizzes_questions`
ADD CONSTRAINT `quizzes_questions_ibfk_1` FOREIGN KEY (`questionid`) REFERENCES `questions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `quizzes_questions_ibfk_2` FOREIGN KEY (`quizid`) REFERENCES `quizzes` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `users`
--
ALTER TABLE `users`
ADD CONSTRAINT `roleid` FOREIGN KEY (`roleid`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `users_ibfk_1` FOREIGN KEY (`ticketid`) REFERENCES `tickets` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
7b6691119d3fe07e52abfff4676716df895de21d | SQL | alex7198/Developpement-Jeu-en-ligne | /BD/projetweb.sql | UTF-8 | 1,245 | 2.890625 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.8.4
-- https://www.phpmyadmin.net/
--
-- Hôte : 127.0.0.1:3306
-- Généré le : mer. 17 avr. 2019 à 13:33
-- Version du serveur : 5.7.24
-- Version de PHP : 5.6.40
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `projetweb`
--
-- --------------------------------------------------------
--
-- Structure de la table `utilisateur`
--
DROP TABLE IF EXISTS `utilisateur`;
CREATE TABLE IF NOT EXISTS `utilisateur` (
`pseudo` varchar(50) NOT NULL,
`mail` varchar(50) NOT NULL,
`mdp` varchar(300) NOT NULL,
`isAdmin` tinyint(1) NOT NULL,
`cle` varchar(300) NOT NULL,
`isActive` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`pseudo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
3d01bf1213532c26420928a6b1a8994bcb3ef8fe | SQL | APregh/Buksza-APregh | /src/main/resources/liquibase/scripts/account-table-create.sql | UTF-8 | 426 | 2.734375 | 3 | [] | no_license | CREATE TABLE ACCOUNT
(
ID BIGINT NOT NULL PRIMARY KEY COMMENT 'Az elsődleges kulcs',
ACCOUNT_NAME VARCHAR(255) NOT NULL COMMENT 'A fiók neve',
AMOUNT BIGINT NOT NULL COMMENT 'A fiókhoz tartozó összeg',
ACCOUNT_TYPE VARCHAR(50) NOT NULL COMMENT 'A fiók típusa'
) DEFAULT CHARSET utf8
COLLATE utf8_general_ci
ENGINE = InnoDB COMMENT = 'A fiókokat tartalmazó tábla';
| true |
99fad13116c305902628745567cb3adb1a58512f | SQL | richhl/TFG_LAMP_ANSIBLE | /roles/mariadb/files/bdd.sql | UTF-8 | 408 | 2.828125 | 3 | [] | no_license | DROP DATABASE IF EXISTS incidencias;
CREATE DATABASE incidencias;
USE incidencias;
CREATE TABLE info(
Nombre VARCHAR(30) NOT NULL,
IP VARCHAR(15) NOT NULL,
Correo VARCHAR(30) NOT NULL,
Departamento VARCHAR(10) NOT NULL,
Asunto VARCHAR(15) NOT NULL,
Descripcion VARCHAR(150) NOT NULL,
CONSTRAINT pk_IP PRIMARY KEY (IP)
);
| true |
30276d0789b8cccdfdf88b58d362fa0e20943e35 | SQL | JmAUDIC/JmAUDIC.github.io | /Ex_Proj_BDD_SQL_L3/AleBD/controle.sql | UTF-8 | 764 | 2.84375 | 3 | [] | no_license |
CREATE ROLE agriculteur;
GRANT INSERT(dateDebT_emp, num_adh, num_mat,dateFinT_emp), UPDATE(remarque_empr) ON EMPRUNT TO agriculteur;
GRANT SELECT on MATERIEL to agriculteur;
GRANT SELECT, INSERT, UPDATE on ENTRETIEN to agriculteur;
GRANT agriculteur to L3_85;
CREATE ROLE secretairebis;
GRANT SELECT, UPDATE(dateDebT_emp,num_mat,dateFinT_emp,dateDebR_emp,dateFinR_emp) on EMPRUNT to secretairebis;
GRANT SELECT, INSERT, UPDATE on MATERIEL to secretairebis;
GRANT SELECT, INSERT, UPDATE on ADHERENT to secretairebis;
GRANT SELECT on ENTRETIEN to secretairebis;
GRANT secretairebis to L3_62;
CREATE ROLE conseiladministration;
GRANT ALL ON MATERIEL;
GRANT ALL ON MATERIEL;
GRANT ALL ON MATERIEL;
GRANT ALL ON MATERIEL;
GRANT conseiladministration TO L3_86; | true |
2b4a48c41557c61e979dca4c8d61c8d33a2d49f4 | SQL | kuchwarh/CSCI2254-Degree-Planner | /sql/creates.sql | UTF-8 | 2,869 | 3.796875 | 4 | [] | no_license | # Drop table queries:
drop table fulfills;
drop table enroll;
drop table slots;
drop table plan;
drop table admins;
drop table students;
drop table reqs;
drop table courses;
drop table fields;
drop table class_cats;
drop table slots;
# Create table for student users:
create table students (id int not null auto_increment, username varchar(15) not null,
password varchar(40) not null, school enum('mcas', 'csom', 'cson', 'lsoe'),
primary key (id)) engine = InnoDB;
# Create table for fields of study:
create table fields_of_study (id int not null auto_increment, name varchar(30) not null,
school enum('mcas', 'csom', 'cson', 'lsoe'), type enum('major', 'minor',
'concentration', 'core'), primary key (id)) engine = InnoDB;
# Create table for class categories:
create table class_cats (id int not null auto_increment, title varchar(100) not null,
primary key (id)) engine = InnoDB;
# Create table for requirements:
create table reqs (id int not null auto_increment, field int not null, class_cat int not
null, number int not null, primary key (id), foreign key (field) references fields_of_study(id), foreign key
(class_cat) references class_cats(id)) engine = InnoDB;
# Create table for courses:
create table courses (id int not null auto_increment, name varchar(100) not null,
dept varchar(30) not null, credits int, primary key (id)) engine = InnoDB;
# Create table for fulfills:
create table fulfills (id int not null auto_increment, req_id int not null, course_id int
not null, primary key (id), foreign key (req_id) references reqs(id), foreign key
(course_id) references courses(id)) engine = InnoDB;
# Create table for enrollment:
create table enroll (id int not null auto_increment, student int not null, field int
not null, current boolean not null, primary key (id), foreign key (student) references
students(id), foreign key (field) references fields_of_study(id)) engine = InnoDB;
# Create table for slots:
create table slots (id int not null auto_increment, semester varchar(10) not null, year
int not null, course_num int not null, primary key (id)) engine = InnoDB;
# Create table for plan:
create table plan (slot int not null, student int not null, req int, course int,
primary key (slot, student), foreign key (slot)
references slots(id), foreign key (student) references students(id), foreign key
(req) references reqs(id), foreign key (course) references courses(id)) engine = InnoDB;
# Create table for APs:
create table aps (id int not null auto_increment, student int not null, req int not null,
primary key (id), foreign key (student) references students(id), foreign key
(req) references reqs(id)) engine = InnoDB;
# Create table for admin users:
create table admins (id int not null auto_increment, username varchar(15) not null,
password varchar(40) not null, primary key (id)) engine = InnoDB; | true |
a2d2366d4f2818551efe9bafd010fd50532bd83c | SQL | AntonNikitenko/Database | /lab4/fill.sql | UTF-8 | 3,509 | 2.609375 | 3 | [] | no_license | insert into building(building_num,building_name) values (1, 'main office');
insert into building(building_num,building_name) values (2, 'security service office');
insert into department(dep_id,dep_name,building_num) values (15, 'administration' , 1);
insert into department(dep_id,dep_name,building_num) values (10, 'bookkeeping office', 1);
insert into department(dep_id,dep_name,building_num) values (9, 'security service ', 2);
insert into room(room_num,room_name,open_time,close_time) values (1,'gen. manager cabinet', '09:00:00', '18:00:00');
insert into room(room_num,room_name,open_time,close_time) values (17,'bookkeeping cabinet 1', '08:00:00', '17:00:00');
insert into room(room_num,room_name,open_time,close_time) values (18,'bookkeeping cabinet 2', '08:00:00', '17:00:00');
insert into room(room_num,room_name,open_time,close_time) values (19,'bookkeeping cabinet 3', '08:00:00', '17:00:00');
insert into room(room_num,room_name,open_time,close_time) values (107,'admission control cabinet', '12:00:00', '16:00:00');
insert into room(room_num,room_name,open_time,close_time) values (115,'videocontrol cabinet', '00:00:00', '00:00:00');
insert into departmentsadmission(dep_id,room_num) values (15, 1);
insert into departmentsadmission(dep_id,room_num) values (15, 17);
insert into departmentsadmission(dep_id,room_num) values (15, 18);
insert into departmentsadmission(dep_id,room_num) values (15, 19);
insert into departmentsadmission(dep_id,room_num) values (10, 17);
insert into departmentsadmission(dep_id,room_num) values (10, 18);
insert into departmentsadmission(dep_id,room_num) values (10, 19);
insert into departmentsadmission(dep_id,room_num) values (9, 107);
insert into departmentsadmission(dep_id,room_num) values (9, 115);
insert into employee(emp_id,full_name,adress,phone_num,post,dep_id) values (1,'Petrov Ivan Fedorovich','Dovatora Street 27.16',+79342222095,'gen.manager',15);
insert into employee(emp_id,full_name,adress,phone_num,post,dep_id) values (2,'Petrova Irina Dmitrievna', 'Kosmonavtov st. 25.83',+79142891097,'accountant',10);
insert into employee(emp_id,full_name,adress,phone_num,post,dep_id) values (3,'Ivanov Arsen Magomedovich', 'Pobedi st 2.3',+79068270952,'security',9);
insert into factualvisit(emp_id,room_num,visit_date,start_of_vis,end_of_vis) values (1, 1, '2015-12-08', '10:22:42', '14:17:07');
insert into factualvisit(emp_id,room_num,visit_date,start_of_vis,end_of_vis) values (1, 18, '2015-12-08', '13:12:57', '13:35:47');
insert into factualvisit(emp_id,room_num,visit_date,start_of_vis,end_of_vis) values (2, 17, '2015-12-08', '08:57:15', '17:07:21');
insert into factualvisit(emp_id,room_num,visit_date,start_of_vis,end_of_vis) values (3, 107, '2015-12-08', '00:05:47', '18:17:32');
insert into periodadmission(emp_id,room_num,week_day,start_of_adm,end_of_adm) values (1, 1, 'wednesday', '00:00:00', '00:00:00');
insert into periodadmission(emp_id,room_num,week_day,start_of_adm,end_of_adm) values (2, 17, 'monday', '09:00:00', '17:00:00');
insert into periodadmission(emp_id,room_num,week_day,start_of_adm,end_of_adm) values (3, 107, 'saturday', '00:06:00', '18:00:00');
insert into temporaryadmission(emp_id,room_num,visit_date,start_of_adm,end_of_adm) values (1, 1, '2015-12-09', '12:00:00', '13:00:00');
insert into temporaryadmission(emp_id,room_num,visit_date,start_of_adm,end_of_adm) values (2, 1, '2015-12-08', '16:30:00', '17:00:00');
insert into temporaryadmission(emp_id,room_num,visit_date,start_of_adm,end_of_adm) values (3, 1, '2015-12-13', '18:00:00', '19:00:00');
| true |
c8061b97abba77d1ee2addf68ad47ca5e049303b | SQL | christolivier/PROJET-GLA-Emploi-du-temps-IFI-2017 | /emploi_temps_ifi.sql | UTF-8 | 6,174 | 3.21875 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.6.5.2
-- https://www.phpmyadmin.net/
--
-- Client : 127.0.0.1
-- Généré le : Jeu 16 Novembre 2017 à 16:52
-- Version du serveur : 10.1.21-MariaDB
-- Version de PHP : 7.1.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `emploi_temps_ifi`
--
-- --------------------------------------------------------
--
-- Structure de la table `emploi`
--
CREATE TABLE `emploi` (
`emploi_id` int(11) NOT NULL,
`course_name` varchar(200) CHARACTER SET utf8 NOT NULL,
`start_date` datetime NOT NULL,
`end_date` datetime NOT NULL,
`color` varchar(64) CHARACTER SET utf8 DEFAULT NULL,
`uid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `emploi`
--
INSERT INTO `emploi` (`emploi_id`, `course_name`, `start_date`, `end_date`, `color`, `uid`) VALUES
(64, 'BEC', '2017-12-30 09:00:00', '2017-12-30 12:00:00', 'null', 10),
(65, 'GLA', '2017-12-31 09:00:00', '2017-12-31 12:00:00', 'null', 10),
(70, ' GES PRO', '2018-01-03 00:00:00', '2018-01-03 00:05:00', '', 36),
(71, 'GSP', '2018-01-04 09:35:00', '2018-01-04 12:35:00', '#FF6699', 10),
(72, 'SMA', '2018-01-03 14:00:00', '2018-01-03 17:00:00', '#FF6699', 10);
-- --------------------------------------------------------
--
-- Structure de la table `events`
--
CREATE TABLE `events` (
`ID_EV` int(11) NOT NULL,
`NOM_EV` varchar(100) NOT NULL,
`DATE_EV` varchar(15) NOT NULL,
`LIEU_EV` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `events`
--
INSERT INTO `events` (`ID_EV`, `NOM_EV`, `DATE_EV`, `LIEU_EV`) VALUES
(2, ' coference sur master data managment', ' 2017-12-22', ' opera hanoi vietnam');
-- --------------------------------------------------------
--
-- Structure de la table `professeur`
--
CREATE TABLE `professeur` (
`ID_PROF` int(11) NOT NULL,
`NOMPRENOM_PROF` varchar(100) NOT NULL,
`COURS` varchar(100) NOT NULL,
`EMAIL` varchar(100) NOT NULL,
`MINICV` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `professeur`
--
INSERT INTO `professeur` (`ID_PROF`, `NOMPRENOM_PROF`, `COURS`, `EMAIL`, `MINICV`) VALUES
(1, ' QUANG NGUYEN', ' REASEAUX ', ' quangnguyen@ifi.edu.vn', 'DOCTEUR DEPUIS 1991, RESPONSABLE DU MASTER 1 A L\'IFI ET RESPOSABLE DE LABORATOIRE UMMCI'),
(2, 'MANH HUONG', 'SMA ', 'manhhounh@gmail.com', 'phd en france professeur a ussth');
-- --------------------------------------------------------
--
-- Structure de la table `promotion`
--
CREATE TABLE `promotion` (
`uid` int(11) NOT NULL,
`promoname` varchar(200) NOT NULL,
`cpassword` varchar(200) NOT NULL,
`status` varchar(10) NOT NULL COMMENT 'check user active or not',
`position` varchar(10) NOT NULL COMMENT 'check user Admin or normal user',
`password` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `promotion`
--
INSERT INTO `promotion` (`uid`, `promoname`, `cpassword`, `status`, `position`, `password`) VALUES
(8, 'christolivier', '03040047Z', 'A', 'A', ''),
(10, 'promotion 21', '12345678', 'A', 'U', ''),
(36, 'promotion 22', '123', 'A', 'U', '123'),
(37, 'promo10', '12345', 'A', 'U', '12345');
-- --------------------------------------------------------
--
-- Structure de la table `setting`
--
CREATE TABLE `setting` (
`uid` int(11) NOT NULL,
`pdf` varchar(10) NOT NULL,
`minc` varchar(10) NOT NULL,
`skin` varchar(10) NOT NULL,
`language` varchar(30) NOT NULL,
`map` varchar(10) NOT NULL,
`agenda` varchar(10) NOT NULL,
`ical` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `setting`
--
INSERT INTO `setting` (`uid`, `pdf`, `minc`, `skin`, `language`, `map`, `agenda`, `ical`) VALUES
(1, 'pdfA', 'mcA', 'sk1', 'English', 'mapA', 'agA', 'icD'),
(2, 'pdfA', 'mcA', 'sk1', 'English', 'mapA', 'agD', 'icD'),
(3, 'pdfD', 'mcD', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(4, 'pdfD', 'mcD', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(5, 'pdfD', 'mcD', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(6, 'pdfA', 'mcA', 'sk1', 'English', 'mapA', 'agA', 'icA'),
(7, 'pdfD', 'mcA', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(8, 'pdfD', 'mcD', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(9, 'pdfA', 'mcA', 'sk1', 'English', 'mapA', 'agA', 'icA'),
(31, 'pdfD', 'mcA', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(32, 'pdfD', 'mcA', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(33, 'pdfD', 'mcA', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(34, 'pdfD', 'mcA', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(35, 'pdfD', 'mcA', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(36, 'pdfD', 'mcA', 'sk1', 'English', 'mapD', 'agD', 'icD'),
(37, 'pdfD', 'mcA', 'sk1', 'English', 'mapD', 'agD', 'icD');
--
-- Index pour les tables exportées
--
--
-- Index pour la table `emploi`
--
ALTER TABLE `emploi`
ADD PRIMARY KEY (`emploi_id`);
--
-- Index pour la table `events`
--
ALTER TABLE `events`
ADD PRIMARY KEY (`ID_EV`);
--
-- Index pour la table `professeur`
--
ALTER TABLE `professeur`
ADD PRIMARY KEY (`ID_PROF`);
--
-- Index pour la table `promotion`
--
ALTER TABLE `promotion`
ADD PRIMARY KEY (`uid`);
--
-- AUTO_INCREMENT pour les tables exportées
--
--
-- AUTO_INCREMENT pour la table `emploi`
--
ALTER TABLE `emploi`
MODIFY `emploi_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=73;
--
-- AUTO_INCREMENT pour la table `events`
--
ALTER TABLE `events`
MODIFY `ID_EV` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT pour la table `professeur`
--
ALTER TABLE `professeur`
MODIFY `ID_PROF` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT pour la table `promotion`
--
ALTER TABLE `promotion`
MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
af0342a5634ffb39d911ead7edf121ccacc6b085 | SQL | biswarup81/patty-bebe | /install/data/GB/GB.sql | UTF-8 | 4,173 | 2.609375 | 3 | [] | no_license | INSERT INTO `lc_currencies` (`status`, `code`, `number`, `name`, `value`, `decimals`, `prefix`, `suffix`, `priority`, `date_updated`, `date_created`) VALUES
(1, 'GBP', '826', 'British Pound', 1.00, 2, '£', '', 0, NOW(), NOW());
-- --------------------------------------------------------
ALTER TABLE `lc_products_prices` ADD `GBP` DECIMAL(11,4) NOT NULL;
-- --------------------------------------------------------
ALTER TABLE `lc_products_campaigns` ADD `GBP` DECIMAL(11,4) NOT NULL;
-- --------------------------------------------------------
ALTER TABLE `lc_products_options` ADD `GBP` DECIMAL(11,4) NOT NULL;
-- --------------------------------------------------------
UPDATE `lc_settings` SET `value` = 'GBP' WHERE `key` in ('store_currency_code', 'default_currency_code');
-- --------------------------------------------------------
UPDATE `lc_currencies` SET `value` = 1.2493 WHERE `code` = 'USD' LIMIT 1;
-- --------------------------------------------------------
UPDATE `lc_currencies` SET `value` = 1.1790 WHERE `code` = 'EUR' LIMIT 1;
-- --------------------------------------------------------
INSERT INTO `lc_geo_zones` (`name`, `description`, `date_updated`, `date_created`) VALUES
('GB VAT Zone', '', NOW(), NOW());
-- --------------------------------------------------------
SET @GB_VAT_ZONE = LAST_INSERT_ID();
-- --------------------------------------------------------
INSERT INTO `lc_zones_to_geo_zones` (`geo_zone_id`, `country_code`, `zone_code`, `date_updated`, `date_created`) VALUES
(@GB_VAT_ZONE, 'GB', '', NOW(), NOW());
-- --------------------------------------------------------
INSERT INTO `lc_geo_zones` (`name`, `description`, `date_updated`, `date_created`) VALUES
('EU VAT Zone', 'European Union excl. GB', NOW(), NOW());
-- --------------------------------------------------------
SET @EU_VAT_ZONE = LAST_INSERT_ID();
-- --------------------------------------------------------
INSERT INTO `lc_zones_to_geo_zones` (`geo_zone_id`, `country_code`, `zone_code`, `date_updated`, `date_created`) VALUES
(@EU_VAT_ZONE, 'AT', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'BE', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'BG', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'CY', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'CZ', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'DE', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'DK', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'EE', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'ES', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'FR', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'FI', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'GR', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'HR', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'HU', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'IE', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'IT', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'LV', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'LT', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'LU', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'MT', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'NL', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'PL', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'PT', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'RO', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'SE', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'SI', '', NOW(), NOW()),
(@EU_VAT_ZONE, 'SK', '', NOW(), NOW());
-- --------------------------------------------------------
INSERT INTO `lc_tax_classes` (`name`, `description`, `date_updated`, `date_created`) VALUES
('Standard', '', NOW(), NOW()),
('Reduced', '', NOW(), NOW());
-- --------------------------------------------------------
INSERT INTO `lc_tax_rates` (`tax_class_id`, `geo_zone_id`, `type`, `name`, `description`, `rate`, `customer_type`, `tax_id_rule`, `date_updated`, `date_created`) VALUES
(1, @GB_VAT_ZONE, 'percent', 'UK VAT 20%', '', 20.0000, 'both', 'both', NOW(), NOW()),
(1, @EU_VAT_ZONE, 'percent', 'UK VAT 20%', '', 20.0000, 'individuals', 'both', NOW(), NOW()),
(1, @EU_VAT_ZONE, 'percent', 'UK VAT 20%', '', 20.0000, 'companies', 'without', NOW(), NOW()),
(2, @GB_VAT_ZONE, 'percent', 'UK VAT 5%', '', 5.0000, 'both', 'both', NOW(), NOW()),
(2, @EU_VAT_ZONE, 'percent', 'UK VAT 5%', '', 5.0000, 'individuals', 'both', NOW(), NOW()),
(2, @EU_VAT_ZONE, 'percent', 'UK VAT 5%', '', 5.0000, 'companies', 'without', NOW(), NOW());
| true |
886aed13160754b1df3d4288b3ccb4215b7b3856 | SQL | cs345team/social | /SocialNetworkWebsite/docs/setup.sql | UTF-8 | 3,220 | 3.5625 | 4 | [] | no_license | DROP DATABASE `social`;
CREATE DATABASE `social`;
USE `social`;
CREATE TABLE `image` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`img` longblob NOT NULL,
PRIMARY KEY (`id`)
) AUTO_INCREMENT = 1;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`passwd` varchar(20) NOT NULL,
`screen_name`varchar(20) NOT NULL,
`real_name` text,
`gender` varchar(6),
`birthday` timestamp,
`interests` text,
`profile_img_id` int(11),
`config` text,
`confirmation_code` char(36),
`confirmation_status` tinyint(1),
PRIMARY KEY(`id`),
UNIQUE KEY `email_UNIQUE` (`email`),
UNIQUE KEY `screenname_UNIQUE` (`screen_name`),
FOREIGN KEY (`profile_img_id`) REFERENCES `image` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) AUTO_INCREMENT = 10000;
CREATE TABLE `wall` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`posted_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
`poster_id` int(11) NOT NULL,
`text` text,
`img_id` int(11),
PRIMARY KEY(`id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY (`poster_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY (`img_id`) REFERENCES `image` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) AUTO_INCREMENT = 1;
CREATE TABLE `friends` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
`friend_id` int(11) NOT NULL,
PRIMARY KEY(`id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY (`friend_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) AUTO_INCREMENT = 1;
CREATE TABLE `requests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`requester_id` int(11) NOT NULL,
`requestee_id` int(11) NOT NULL,
PRIMARY KEY(`id`),
FOREIGN KEY (`requester_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY (`requestee_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) AUTO_INCREMENT = 1;
CREATE TABLE `invite_code` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`code` char(36) NOT NULL,
`created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(`id`),
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) AUTO_INCREMENT = 1;
INSERT INTO user(email, passwd, screen_name, confirmation_status) VALUES ('admin@suffolk.edu', 'admin', 'Administrator', 1);
INSERT INTO user(email, passwd, screen_name, confirmation_status) VALUES ('a@suffolk.edu', 'admin', 'Tom', 1);
INSERT INTO user(email, passwd, screen_name, confirmation_status) VALUES ('b@suffolk.edu', 'admin', 'John', 1);
INSERT INTO user(email, passwd, screen_name, confirmation_status) VALUES ('c@suffolk.edu', 'admin', 'Jerry', 1);
INSERT INTO invite_code(user_id, code) VALUES ('10000', 'ebfcf0c5-71ed-4735-a7af-7c2a4d8d5d8f');
INSERT INTO invite_code(user_id, code) VALUES ('10000', 'bcdda4dd-abc9-4b4e-9db0-c4fd63d9f519');
INSERT INTO invite_code(user_id, code) VALUES ('10000', '2e701bed-9601-46b7-be46-c8b63b29e7b6');
| true |
02205e14445897f25ef1ca83563ca180d344babf | SQL | edmundham/SchoolAssignment | /3rdTerm/jsf/COMP3910_assignment3/db.sql | UTF-8 | 14,704 | 3.65625 | 4 | [] | no_license | drop database if exists schedule;
CREATE DATABASE schedule;
drop user if exists 'admin_user'@'localhost';
drop user if exists 'admin_user'@'%';
CREATE USER 'admin_user'@'localhost' IDENTIFIED BY 'admin_user';
CREATE USER 'admin_user'@'%' IDENTIFIED BY 'admin_user';
GRANT ALL ON schedule.* TO 'admin_user'@'localhost';
GRANT ALL ON schedule.* TO 'admin_user'@'%';
USE schedule;
DROP TABLE IF EXISTS Employee;
CREATE TABLE Employee(
employeeid integer auto_increment primary key,
firstname varchar(256),
lastname varchar(256),
username varchar(256),
password varchar(256),
createddate timestamp,
isadmin boolean
);
INSERT INTO Employee (firstname, lastname, username, password, createddate, isadmin)
VALUES('Test', 'Test', 'Test123Test123', 'Test123Test123', now(), 1);
INSERT INTO Employee (firstname, lastname, username, password, createddate, isadmin)
VALUES('Cameron', 'Lay', 'Cam.Lay123', 'Cam.Lay123', now(), 0);
INSERT INTO Employee (firstname, lastname, username, password, createddate, isadmin)
VALUES('Edmund', 'Ham', 'Edmund.Ham123', 'Edmund.Ham123', now(), 0);
INSERT INTO Employee (firstname, lastname, username, password, createddate, isadmin)
VALUES('Danny', 'Di Iorio', 'Danny.Di.Iorio123', 'Danny.Di.Iorio123', now(), 0);
INSERT INTO Employee (firstname, lastname, username, password, createddate, isadmin)
VALUES('Tony', 'Pacheco', 'Tony.Pacheco123', 'Tony.Pacheco123', now(), 0);
INSERT INTO Employee (firstname, lastname, username, password, createddate, isadmin)
VALUES('Bruce', 'Link', 'Bruce.Link123', 'Bruce.Link123', now(), 0);
INSERT INTO Employee (firstname, lastname, username, password, createddate, isadmin)
VALUES('Trevor', 'Lord', 'Trevor.Lord123', 'Trevor.Lord123', now(), 0);
drop table if exists token;
create table token(
token varchar(256) primary key,
employeeid integer,
datecreated timestamp,
expirydate timestamp,
isadmin boolean,
username varchar(256),
isactive boolean
);
drop table if exists timesheet;
create table timesheet(
timesheetid integer auto_increment primary key,
employeeid integer,
endweek timestamp,
startweek timestamp
);
insert into timesheet (employeeid, endweek, startweek)
values(1,
(SELECT TIMESTAMP('2018-11-09')),
(select timestamp('2018-11-03'))
);
insert into timesheet (employeeid, endweek, startweek)
values(1,
(SELECT TIMESTAMP('2018-11-16')),
(select timestamp('2018-11-10'))
);
insert into timesheet (employeeid, endweek, startweek)
values(2,
(SELECT TIMESTAMP('2018-11-09')),
(select timestamp('2018-11-03'))
);
insert into timesheet (employeeid, endweek, startweek)
values(2,
(SELECT TIMESTAMP('2018-11-16')),
(select timestamp('2018-11-10'))
);
insert into timesheet (employeeid, endweek, startweek)
values(3,
(SELECT TIMESTAMP('2018-11-09')),
(select timestamp('2018-11-03'))
);
insert into timesheet (employeeid, endweek, startweek)
values(3,
(SELECT TIMESTAMP('2018-11-16')),
(select timestamp('2018-11-10'))
);
insert into timesheet (employeeid, endweek, startweek)
values(4,
(SELECT TIMESTAMP('2018-11-09')),
(select timestamp('2018-11-03'))
);
insert into timesheet (employeeid, endweek, startweek)
values(4,
(SELECT TIMESTAMP('2018-11-16')),
(select timestamp('2018-11-10'))
);
insert into timesheet (employeeid, endweek, startweek)
values(5,
(SELECT TIMESTAMP('2018-11-09')),
(select timestamp('2018-11-03'))
);
insert into timesheet (employeeid, endweek, startweek)
values(5,
(SELECT TIMESTAMP('2018-11-16')),
(select timestamp('2018-11-10'))
);
DROP TABLE IF EXISTS TimesheetRow;
CREATE TABLE timesheetrow(
timesheetrowid integer auto_increment primary key,
timesheetid integer,
projectid integer,
workpackage varchar(256),
monday integer,
tuesday integer,
wednesday integer,
thursday integer,
friday integer,
saturday integer,
sunday integer,
notes varchar(256)
);
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(1, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'Made database working');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(1, 2, 'wp1', 8, 8, 8, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(1, 3, 'wp1', 8, 8, 8, 10, 6, 0, 0, 'Set up model classes');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(1, 1, 'wp2', 7, 9, 8, 8, 8, 0, 0, 'Set up controllers');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(1, 2, 'wp2', 9, 9, 9, 9, 9, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(2, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'Made database working');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(2, 2, 'wp1', 8, 8, 8, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(2, 3, 'wp1', 8, 8, 8, 10, 6, 0, 0, 'Set up model classes');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(2, 1, 'wp2', 7, 9, 8, 8, 8, 0, 0, 'Set up controllers');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(2, 2, 'wp2', 9, 9, 9, 9, 9, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(3, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(3, 2, 'wp1', 7, 7, 7, 7, 9, 0, 0, 'Knowledge transfer to team in London');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(3, 3, 'wp1', 8, 6, 6, 7, 9, 0, 0, 'Set up development environment');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(3, 1, 'wp2', 9, 7, 5, 4, 4, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(3, 2, 'wp2', 5, 5, 5, 4, 4, 0, 0, 'Selling');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(4, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(4, 2, 'wp1', 7, 7, 7, 7, 9, 0, 0, 'Knowledge transfer to team in London');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(4, 3, 'wp1', 8, 6, 6, 7, 9, 0, 0, 'Set up development environment');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(4, 1, 'wp2', 9, 7, 5, 4, 4, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(4, 2, 'wp2', 5, 5, 5, 4, 4, 0, 0, 'Selling');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(5, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(5, 2, 'wp1', 7, 7, 7, 7, 9, 0, 0, 'Knowledge transfer to team in London');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(5, 3, 'wp1', 8, 6, 6, 7, 9, 0, 0, 'Set up development environment');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(5, 1, 'wp2', 9, 7, 5, 4, 4, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(5, 2, 'wp2', 5, 5, 5, 4, 4, 0, 0, 'Selling');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(6, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(6, 2, 'wp1', 7, 7, 7, 7, 9, 0, 0, 'Knowledge transfer to team in London');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(6, 3, 'wp1', 8, 6, 6, 7, 9, 0, 0, 'Set up development environment');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(6, 1, 'wp2', 9, 7, 5, 4, 4, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(6, 2, 'wp2', 5, 5, 5, 4, 4, 0, 0, 'Selling');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(7, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(7, 2, 'wp1', 7, 7, 7, 7, 9, 0, 0, 'Knowledge transfer to team in London');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(7, 3, 'wp1', 8, 6, 6, 7, 9, 0, 0, 'Set up development environment');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(7, 1, 'wp2', 9, 7, 5, 4, 4, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(7, 2, 'wp2', 5, 5, 5, 4, 4, 0, 0, 'Selling');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(8, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(8, 2, 'wp1', 7, 7, 7, 7, 9, 0, 0, 'Knowledge transfer to team in London');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(8, 3, 'wp1', 8, 6, 6, 7, 9, 0, 0, 'Set up development environment');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(8, 1, 'wp2', 9, 7, 5, 4, 4, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(8, 2, 'wp2', 5, 5, 5, 4, 4, 0, 0, 'Selling');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(9, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(9, 2, 'wp1', 7, 7, 7, 7, 9, 0, 0, 'Knowledge transfer to team in London');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(9, 3, 'wp1', 8, 6, 6, 7, 9, 0, 0, 'Set up development environment');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(9, 1, 'wp2', 9, 7, 5, 4, 4, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(9, 2, 'wp2', 5, 5, 5, 4, 4, 0, 0, 'Selling');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(10, 1, 'wp1', 5, 2, 3, 7, 9, 0, 0, 'UX/UI design');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(10, 2, 'wp1', 7, 7, 7, 7, 9, 0, 0, 'Knowledge transfer to team in London');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(10, 3, 'wp1', 8, 6, 6, 7, 9, 0, 0, 'Set up development environment');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(10, 1, 'wp2', 9, 7, 5, 4, 4, 0, 0, 'Final presentation');
insert into timesheetrow (timesheetid, projectid, workpackage, monday, tuesday, wednesday, thursday, friday, saturday, sunday, notes)
values(10, 2, 'wp2', 5, 5, 5, 4, 4, 0, 0, 'Selling');
drop procedure if exists deactivatetoken;
DELIMITER //
CREATE PROCEDURE deactivatetoken()
BEGIN
update token
set isactive = false
where expirydate < now();
END //
DELIMITER ;
CREATE EVENT myevent
ON SCHEDULE EVERY 86400 SECOND
DO
CALL delete_rows_links(); | true |
0146262c3b12b2e7369d529890609016f544a64c | SQL | cda-cambrai/php-oo | /11-tp/vtc.sql | UTF-8 | 1,564 | 3.265625 | 3 | [] | no_license | -- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema vtc
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema vtc
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `vtc` DEFAULT CHARACTER SET utf8 ;
USE `vtc` ;
-- -----------------------------------------------------
-- Table `vtc`.`driver`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vtc`.`driver` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`firstname` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `vtc`.`vehicle`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `vtc`.`vehicle` (
`id` INT NOT NULL AUTO_INCREMENT,
`brand` VARCHAR(255) NOT NULL,
`color` VARCHAR(255) NOT NULL,
`model` VARCHAR(255) NOT NULL,
`registration` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `registration_UNIQUE` (`registration` ASC))
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
| true |
de079305fae41abe84cf28bf72f52e64d7fa16b1 | SQL | roberko44/Buecherhandel24 | /database/sql/finanzstudi.sql | UTF-8 | 5,954 | 3.25 | 3 | [
"MIT"
] | permissive | SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
CREATE TABLE `buch` (
`BUCHID` int(11) NOT NULL,
`NUTZERID` int(11) NOT NULL,
`KATEGORIEID` int(11) NOT NULL,
`UNTERKATEGORIEID` int(11) DEFAULT NULL,
`BUCHNAME` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
`BESCHREIBUNG` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
`ERSCHEINUNGSDATUM` date DEFAULT NULL,
`AUTOR` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
`BILD` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
`BUCHINHALT` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `buch` (`BUCHID`, `NUTZERID`, `KATEGORIEID`, `UNTERKATEGORIEID`, `BUCHNAME`, `BESCHREIBUNG`, `ERSCHEINUNGSDATUM`, `AUTOR`, `BILD`, `BUCHINHALT`) VALUES
(1, 1, 2, NULL, 'Endlich mit Aktien Geld verdienen', 'Die Strategien und Techniken die Erfolg versprechen', '2012-04-01', 'Max Otte', 'img/Endlich mit Aktien Geld verdienen_ Die Strategien und Techniken, die Erfolg versprechen.jpg', 'pdf/Endlich mit Aktien Geld verdienen_ Die Strategien und Techniken, die Erfolg versprechen.pdf'),
(2, 1, 1, NULL, 'Finanzierung', 'Anleihen, Aktien, Optionen', '2015-05-01', 'Thomas Schuster, Margarita Uskova', 'img/Finanzierung_ Anleihen, Aktien, Optionen.jpg', 'pdf/Finanzierung_ Anleihen, Aktien, Optionen.pdf'),
(3, 1, 3, NULL, 'Mathematik - Motor der Wirtschaft', 'Initiative der Wirtschaft zum Jahr der Mathematik', '2008-02-01', 'Gert-Martin Greuel, Reinhold Remmert, Gerhard Rupprecht', 'img/Mathematik - Motor der Wirtschaft_ Initiative der Wirtschaft zum Jahr der Mathematik.jpg', 'pdf/Mathematik - Motor der Wirtschaft_ Initiative der Wirtschaft zum Jahr der Mathematik.pdf'),
(4, 2, 2, NULL, ' Stock Investing for Dummies ', 'Get savvy tips on todays best investment opportunities and pitfalls', '2006-01-01', 'Paul Mladjenovic', 'img/Stock investing for Dummies.jpg', 'pdf/Stock investing for Dummies.pdf'),
(5, 2, 4, 1, ' Immobilien zum halben Preis! ', 'Tipps, Tricks und Strategien, um zur eigenen Immobilie zum Schnäppchenpreis zu kommen', '2012-02-01', 'Alexander Leary', 'img/Immobilien zum halben Preis! - Tipps, Tricks und Strategien, um zur eigenen Immobilie zum Schnaeppchenpreis zu kommen.jpg', 'pdf/Immobilien zum halben Preis! - Tipps, Tricks und Strategien, um zur eigenen Immobilie zum Schnaeppchenpreis zu kommen.pdf');
CREATE TABLE `kategorie` (
`KATEGORIEID` int(11) NOT NULL,
`KATEGORIENAME` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `kategorie` (`KATEGORIEID`, `KATEGORIENAME`) VALUES
(1, 'Fonds'),
(2, 'Aktien'),
(3, 'Steuern'),
(4, 'Immobilien');
CREATE TABLE `kommentar` (
`KOMMENTARID` int(11) NOT NULL,
`BUCHID` int(11) NOT NULL,
`NUTZERID` int(11) NOT NULL,
`KOMMENTAR` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
`DATUM` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `nutzer` (
`NUTZERID` int(11) NOT NULL,
`NUTZERNAME` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
`PASSWORT` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `nutzer` (`NUTZERID`, `NUTZERNAME`, `PASSWORT`) VALUES
(1, 'zernabze', 'ayy'),
(2, 'dilarako', 'ayy');
CREATE TABLE `unterkategorie` (
`UNTERKATEGORIEID` int(11) NOT NULL,
`KATEGORIEID` int(11) NOT NULL,
`UNTERKATEGORIENAME` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `unterkategorie` (`UNTERKATEGORIEID`, `KATEGORIEID`, `UNTERKATEGORIENAME`) VALUES
(1, 4, 'Ratgeber');
ALTER TABLE `buch`
ADD PRIMARY KEY (`BUCHID`),
ADD KEY `FK_BUCH_HAT_KATEGORI` (`KATEGORIEID`),
ADD KEY `FK_BUCH_KANN_HABE_UNTERKAT` (`UNTERKATEGORIEID`),
ADD KEY `FK_BUCH_VERWALTET_NUTZER` (`NUTZERID`);
ALTER TABLE `kategorie`
ADD PRIMARY KEY (`KATEGORIEID`);
ALTER TABLE `kommentar`
ADD PRIMARY KEY (`KOMMENTARID`),
ADD KEY `FK_KOMMENTA_ENTHAELT_BUCH` (`BUCHID`),
ADD KEY `FK_KOMMENTA_GEHOERT_Z_NUTZER` (`NUTZERID`);
ALTER TABLE `nutzer`
ADD PRIMARY KEY (`NUTZERID`);
ALTER TABLE `unterkategorie`
ADD PRIMARY KEY (`UNTERKATEGORIEID`),
ADD KEY `FK_UNTERKAT_BESITZT_KATEGORI` (`KATEGORIEID`);
ALTER TABLE `buch`
MODIFY `BUCHID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
ALTER TABLE `kategorie`
MODIFY `KATEGORIEID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
ALTER TABLE `kommentar`
MODIFY `KOMMENTARID` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `nutzer`
MODIFY `NUTZERID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
ALTER TABLE `unterkategorie`
MODIFY `UNTERKATEGORIEID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
ALTER TABLE `buch`
ADD CONSTRAINT `FK_BUCH_HAT_KATEGORI` FOREIGN KEY (`KATEGORIEID`) REFERENCES `kategorie` (`KATEGORIEID`),
ADD CONSTRAINT `FK_BUCH_KANN_HABE_UNTERKAT` FOREIGN KEY (`UNTERKATEGORIEID`) REFERENCES `unterkategorie` (`UNTERKATEGORIEID`),
ADD CONSTRAINT `FK_BUCH_VERWALTET_NUTZER` FOREIGN KEY (`NUTZERID`) REFERENCES `nutzer` (`NUTZERID`);
ALTER TABLE `kommentar`
ADD CONSTRAINT `FK_KOMMENTA_ENTHAELT_BUCH` FOREIGN KEY (`BUCHID`) REFERENCES `buch` (`BUCHID`),
ADD CONSTRAINT `FK_KOMMENTA_GEHOERT_Z_NUTZER` FOREIGN KEY (`NUTZERID`) REFERENCES `nutzer` (`NUTZERID`);
ALTER TABLE `unterkategorie`
ADD CONSTRAINT `FK_UNTERKAT_BESITZT_KATEGORI` FOREIGN KEY (`KATEGORIEID`) REFERENCES `kategorie` (`KATEGORIEID`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
7b5bc7131b3f3e8d721edba6a3c13daa40213141 | SQL | silence-do-good/stress-test-Postgres-and-MySQL | /dump/low/day25/select2200.sql | UTF-8 | 178 | 2.625 | 3 | [] | no_license |
SELECT timeStamp, temperature FROM ThermometerOBSERVATION o
WHERE timestamp>'2017-11-24T22:00:00Z' AND timestamp<'2017-11-25T22:00:00Z' AND temperature>=21 AND temperature<=22
| true |
e3e773822dae1ff533c529517a965ae110ec61f9 | SQL | vetronog/DB | /lab4.sql | UTF-8 | 5,786 | 3.3125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1
-- Время создания: Май 26 2017 г., 16:31
-- Версия сервера: 5.7.14
-- Версия PHP: 5.6.25
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `lab4`
--
-- --------------------------------------------------------
--
-- Структура таблицы `athlete`
--
CREATE TABLE `athlete` (
`id_athlete` int(11) NOT NULL,
`full_name` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL,
`growth` int(11) DEFAULT NULL,
`weight` int(11) DEFAULT NULL,
`rating` int(11) DEFAULT NULL,
`birth_day` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Структура таблицы `competition`
--
CREATE TABLE `competition` (
`id_competition` int(11) NOT NULL,
`action_type` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL,
`price` int(11) DEFAULT NULL,
`date_competition` date DEFAULT NULL,
`id_sponsor` int(11) DEFAULT NULL,
`id_location` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Структура таблицы `location`
--
CREATE TABLE `location` (
`id_location` int(11) NOT NULL,
`country` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL,
`id_competition` int(11) DEFAULT NULL,
`town` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Структура таблицы `perfomance`
--
CREATE TABLE `perfomance` (
`id_perfomance` int(11) NOT NULL,
`id_competition` int(11) DEFAULT NULL,
`id_athlete` int(11) DEFAULT NULL,
`perfomance_result` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Структура таблицы `sponsors`
--
CREATE TABLE `sponsors` (
`id_sponsor` int(11) NOT NULL,
`delegate` varchar(11) COLLATE utf8_unicode_ci DEFAULT NULL,
`contribution` int(11) DEFAULT NULL,
`id_competition` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `athlete`
--
ALTER TABLE `athlete`
ADD PRIMARY KEY (`id_athlete`);
--
-- Индексы таблицы `competition`
--
ALTER TABLE `competition`
ADD PRIMARY KEY (`id_competition`),
ADD KEY `id_sponsor` (`id_sponsor`),
ADD KEY `id_location` (`id_location`);
--
-- Индексы таблицы `location`
--
ALTER TABLE `location`
ADD PRIMARY KEY (`id_location`),
ADD KEY `id_competition` (`id_competition`);
--
-- Индексы таблицы `perfomance`
--
ALTER TABLE `perfomance`
ADD PRIMARY KEY (`id_perfomance`),
ADD UNIQUE KEY `id_competition` (`id_competition`,`id_athlete`),
ADD UNIQUE KEY `id_competition_2` (`id_competition`),
ADD KEY `id_competition_3` (`id_competition`),
ADD KEY `id_athlete` (`id_athlete`);
--
-- Индексы таблицы `sponsors`
--
ALTER TABLE `sponsors`
ADD PRIMARY KEY (`id_sponsor`),
ADD KEY `id_competition` (`id_competition`),
ADD KEY `id_competition_2` (`id_competition`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `athlete`
--
ALTER TABLE `athlete`
MODIFY `id_athlete` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT для таблицы `competition`
--
ALTER TABLE `competition`
MODIFY `id_competition` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT для таблицы `location`
--
ALTER TABLE `location`
MODIFY `id_location` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT для таблицы `perfomance`
--
ALTER TABLE `perfomance`
MODIFY `id_perfomance` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT для таблицы `sponsors`
--
ALTER TABLE `sponsors`
MODIFY `id_sponsor` int(11) NOT NULL AUTO_INCREMENT;
--
-- Ограничения внешнего ключа сохраненных таблиц
--
--
-- Ограничения внешнего ключа таблицы `competition`
--
ALTER TABLE `competition`
ADD CONSTRAINT `competition_ibfk_2` FOREIGN KEY (`id_location`) REFERENCES `location` (`id_location`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `competition_ibfk_3` FOREIGN KEY (`id_sponsor`) REFERENCES `sponsors` (`id_sponsor`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `location`
--
ALTER TABLE `location`
ADD CONSTRAINT `location_ibfk_1` FOREIGN KEY (`id_competition`) REFERENCES `competition` (`id_competition`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Ограничения внешнего ключа таблицы `perfomance`
--
ALTER TABLE `perfomance`
ADD CONSTRAINT `perfomance_ibfk_1` FOREIGN KEY (`id_competition`) REFERENCES `competition` (`id_competition`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `perfomance_ibfk_2` FOREIGN KEY (`id_athlete`) REFERENCES `athlete` (`id_athlete`) ON DELETE NO ACTION ON UPDATE NO ACTION;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
be4ad718d0f75791d1902e34585edcde48cffc32 | SQL | pgcodekeeper/pgcodekeeper | /ru.taximaxim.codekeeper.core.tests/src/main/resources/ru/taximaxim/codekeeper/core/drop_trigger_another_schema_new.sql | UTF-8 | 1,156 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | --
-- PostgreSQL database dump
--
SET client_encoding = 'UTF8';
SET check_function_bodies = false;
SET client_min_messages = warning;
--
-- Name: another_triggers; Type: SCHEMA; Schema: -; Owner: postgres
--
CREATE SCHEMA another_triggers;
ALTER SCHEMA another_triggers OWNER TO postgres;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
--
--CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
--COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET search_path = pg_catalog;
--
-- Name: test_table; Type: TABLE; Schema: another_triggers; Owner: postgres; Tablespace:
--
CREATE TABLE another_triggers.test_table_a (
id integer NOT NULL
);
ALTER TABLE another_triggers.test_table_a OWNER TO postgres;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: public; Type: ACL; Schema: -; Owner: postgres
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM postgres;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO PUBLIC;
--
-- PostgreSQL database dump complete
--
| true |
472f668b2e4cdd119383ddb383d2b48ea97a39f1 | SQL | jacksontj/dataman | /sql/dataman_storage/dataman_storage_007.sql | UTF-8 | 12,071 | 2.90625 | 3 | [
"MIT"
] | permissive | /*
Navicat PGSQL Data Transfer
Source Server : local
Source Server Version : 90602
Source Host : localhost:5432
Source Database : dataman_storage
Source Schema : public
Target Server Type : PGSQL
Target Server Version : 90602
File Encoding : 65001
Date: 2017-05-31 11:38:50
*/
-- ----------------------------
-- Sequence structure for collection__id_seq
-- ----------------------------
DROP SEQUENCE IF EXISTS "public"."collection__id_seq";
CREATE SEQUENCE "public"."collection__id_seq"
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 871
CACHE 1;
SELECT setval('"public"."collection__id_seq"', 871, true);
-- ----------------------------
-- Sequence structure for collection_field__id_seq
-- ----------------------------
DROP SEQUENCE IF EXISTS "public"."collection_field__id_seq";
CREATE SEQUENCE "public"."collection_field__id_seq"
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 2399
CACHE 1;
SELECT setval('"public"."collection_field__id_seq"', 2399, true);
-- ----------------------------
-- Sequence structure for collection_field_relation__id_seq
-- ----------------------------
DROP SEQUENCE IF EXISTS "public"."collection_field_relation__id_seq";
CREATE SEQUENCE "public"."collection_field_relation__id_seq"
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 94
CACHE 1;
SELECT setval('"public"."collection_field_relation__id_seq"', 94, true);
-- ----------------------------
-- Sequence structure for collection_index__id_seq
-- ----------------------------
DROP SEQUENCE IF EXISTS "public"."collection_index__id_seq";
CREATE SEQUENCE "public"."collection_index__id_seq"
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 875
CACHE 1;
SELECT setval('"public"."collection_index__id_seq"', 875, true);
-- ----------------------------
-- Sequence structure for collection_index_item__id_seq
-- ----------------------------
DROP SEQUENCE IF EXISTS "public"."collection_index_item__id_seq";
CREATE SEQUENCE "public"."collection_index_item__id_seq"
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 2342
CACHE 1;
SELECT setval('"public"."collection_index_item__id_seq"', 2342, true);
-- ----------------------------
-- Sequence structure for database__id_seq
-- ----------------------------
DROP SEQUENCE IF EXISTS "public"."database__id_seq";
CREATE SEQUENCE "public"."database__id_seq"
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 284
CACHE 1;
SELECT setval('"public"."database__id_seq"', 284, true);
-- ----------------------------
-- Sequence structure for shard_instance__id_seq
-- ----------------------------
DROP SEQUENCE IF EXISTS "public"."shard_instance__id_seq";
CREATE SEQUENCE "public"."shard_instance__id_seq"
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 290
CACHE 1;
SELECT setval('"public"."shard_instance__id_seq"', 290, true);
-- ----------------------------
-- Table structure for collection
-- ----------------------------
DROP TABLE IF EXISTS "public"."collection";
CREATE TABLE "public"."collection" (
"_id" int4 DEFAULT nextval('collection__id_seq'::regclass) NOT NULL,
"name" varchar(255) COLLATE "default",
"shard_instance_id" int4 NOT NULL,
"provision_state" int4 NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for collection_field
-- ----------------------------
DROP TABLE IF EXISTS "public"."collection_field";
CREATE TABLE "public"."collection_field" (
"_id" int4 DEFAULT nextval('collection_field__id_seq'::regclass) NOT NULL,
"name" varchar(255) COLLATE "default",
"collection_id" int4,
"field_type" varchar(255) COLLATE "default",
"field_type_args" jsonb,
"parent_collection_field_id" int4,
"provision_state" int4 NOT NULL,
"not_null" bool NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for collection_field_relation
-- ----------------------------
DROP TABLE IF EXISTS "public"."collection_field_relation";
CREATE TABLE "public"."collection_field_relation" (
"_id" int4 DEFAULT nextval('collection_field_relation__id_seq'::regclass) NOT NULL,
"collection_field_id" int4 NOT NULL,
"relation_collection_field_id" int4 NOT NULL,
"cascade_on_delete" bool NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for collection_index
-- ----------------------------
DROP TABLE IF EXISTS "public"."collection_index";
CREATE TABLE "public"."collection_index" (
"_id" int4 DEFAULT nextval('collection_index__id_seq'::regclass) NOT NULL,
"name" varchar(255) COLLATE "default",
"collection_id" int4,
"unique" bool,
"provision_state" int4 NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for collection_index_item
-- ----------------------------
DROP TABLE IF EXISTS "public"."collection_index_item";
CREATE TABLE "public"."collection_index_item" (
"_id" int4 DEFAULT nextval('collection_index_item__id_seq'::regclass) NOT NULL,
"collection_index_id" int4 NOT NULL,
"collection_field_id" int4 NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for database
-- ----------------------------
DROP TABLE IF EXISTS "public"."database";
CREATE TABLE "public"."database" (
"_id" int4 DEFAULT nextval('database__id_seq'::regclass) NOT NULL,
"name" varchar(255) COLLATE "default",
"provision_state" int4 NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for shard_instance
-- ----------------------------
DROP TABLE IF EXISTS "public"."shard_instance";
CREATE TABLE "public"."shard_instance" (
"_id" int4 DEFAULT nextval('shard_instance__id_seq'::regclass) NOT NULL,
"name" varchar(255) COLLATE "default",
"database_id" int4 NOT NULL,
"count" int4,
"instance" int4,
"database_shard" bool NOT NULL,
"collection_shard" bool NOT NULL,
"provision_state" int4 NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Alter Sequences Owned By
-- ----------------------------
ALTER SEQUENCE "public"."collection__id_seq" OWNED BY "collection"."_id";
ALTER SEQUENCE "public"."collection_field__id_seq" OWNED BY "collection_field"."_id";
ALTER SEQUENCE "public"."collection_field_relation__id_seq" OWNED BY "collection_field_relation"."_id";
ALTER SEQUENCE "public"."collection_index__id_seq" OWNED BY "collection_index"."_id";
ALTER SEQUENCE "public"."collection_index_item__id_seq" OWNED BY "collection_index_item"."_id";
ALTER SEQUENCE "public"."database__id_seq" OWNED BY "database"."_id";
ALTER SEQUENCE "public"."shard_instance__id_seq" OWNED BY "shard_instance"."_id";
-- ----------------------------
-- Indexes structure for table collection
-- ----------------------------
CREATE UNIQUE INDEX "collection_name_shard_instance_id_idx" ON "public"."collection" USING btree ("name", "shard_instance_id");
-- ----------------------------
-- Primary Key structure for table collection
-- ----------------------------
ALTER TABLE "public"."collection" ADD PRIMARY KEY ("_id");
-- ----------------------------
-- Indexes structure for table collection_field
-- ----------------------------
CREATE UNIQUE INDEX "index_collection_field_collection_field_name" ON "public"."collection_field" USING btree ("collection_id", "name");
-- ----------------------------
-- Primary Key structure for table collection_field
-- ----------------------------
ALTER TABLE "public"."collection_field" ADD PRIMARY KEY ("_id");
-- ----------------------------
-- Primary Key structure for table collection_field_relation
-- ----------------------------
ALTER TABLE "public"."collection_field_relation" ADD PRIMARY KEY ("_id");
-- ----------------------------
-- Indexes structure for table collection_index
-- ----------------------------
CREATE UNIQUE INDEX "collection_index_name" ON "public"."collection_index" USING btree ("name", "collection_id");
-- ----------------------------
-- Primary Key structure for table collection_index
-- ----------------------------
ALTER TABLE "public"."collection_index" ADD PRIMARY KEY ("_id");
-- ----------------------------
-- Indexes structure for table collection_index_item
-- ----------------------------
CREATE UNIQUE INDEX "collection_index_item_collection_index_id_collection_field__idx" ON "public"."collection_index_item" USING btree ("collection_index_id", "collection_field_id");
-- ----------------------------
-- Primary Key structure for table collection_index_item
-- ----------------------------
ALTER TABLE "public"."collection_index_item" ADD PRIMARY KEY ("_id");
-- ----------------------------
-- Indexes structure for table database
-- ----------------------------
CREATE UNIQUE INDEX "database_name_idx" ON "public"."database" USING btree ("name");
-- ----------------------------
-- Primary Key structure for table database
-- ----------------------------
ALTER TABLE "public"."database" ADD PRIMARY KEY ("_id");
-- ----------------------------
-- Indexes structure for table shard_instance
-- ----------------------------
CREATE UNIQUE INDEX "shard_instance_name_database_id_idx" ON "public"."shard_instance" USING btree ("name", "database_id");
CREATE UNIQUE INDEX "shard_instance_database_id_count_instance_database_shard_co_idx" ON "public"."shard_instance" USING btree ("database_id", "count", "instance", "database_shard", "collection_shard", "name");
-- ----------------------------
-- Primary Key structure for table shard_instance
-- ----------------------------
ALTER TABLE "public"."shard_instance" ADD PRIMARY KEY ("_id");
-- ----------------------------
-- Foreign Key structure for table "public"."collection"
-- ----------------------------
ALTER TABLE "public"."collection" ADD FOREIGN KEY ("shard_instance_id") REFERENCES "public"."shard_instance" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ----------------------------
-- Foreign Key structure for table "public"."collection_field"
-- ----------------------------
ALTER TABLE "public"."collection_field" ADD FOREIGN KEY ("parent_collection_field_id") REFERENCES "public"."collection_field" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE "public"."collection_field" ADD FOREIGN KEY ("collection_id") REFERENCES "public"."collection" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ----------------------------
-- Foreign Key structure for table "public"."collection_field_relation"
-- ----------------------------
ALTER TABLE "public"."collection_field_relation" ADD FOREIGN KEY ("collection_field_id") REFERENCES "public"."collection_field" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE "public"."collection_field_relation" ADD FOREIGN KEY ("relation_collection_field_id") REFERENCES "public"."collection_field" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ----------------------------
-- Foreign Key structure for table "public"."collection_index"
-- ----------------------------
ALTER TABLE "public"."collection_index" ADD FOREIGN KEY ("collection_id") REFERENCES "public"."collection" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ----------------------------
-- Foreign Key structure for table "public"."collection_index_item"
-- ----------------------------
ALTER TABLE "public"."collection_index_item" ADD FOREIGN KEY ("collection_index_id") REFERENCES "public"."collection_index" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE "public"."collection_index_item" ADD FOREIGN KEY ("collection_field_id") REFERENCES "public"."collection_field" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
-- ----------------------------
-- Foreign Key structure for table "public"."shard_instance"
-- ----------------------------
ALTER TABLE "public"."shard_instance" ADD FOREIGN KEY ("database_id") REFERENCES "public"."database" ("_id") ON DELETE NO ACTION ON UPDATE NO ACTION;
| true |
eeff28f78a2bfe2ddc28eb486a5e7fc2a8350b16 | SQL | gyp/valasztas-adatbazis | /queries/ervenytelen_listas_egyeni_diff.sql | UTF-8 | 1,298 | 3.78125 | 4 | [] | no_license | SELECT
ervenytelen_egyeni.valasztokorzet,
ervenytelen_listas.ervenytelen_szavazolapok AS ervenytelen_szavazolapok_listas,
ervenytelen_egyeni.ervenytelen_szavazolapok AS ervenytelen_szavazolapok_egyeni,
ervenytelen_listas.ervenytelen_szavazolapok - ervenytelen_egyeni.ervenytelen_szavazolapok AS ervenytelen_szavazolapok_diff
FROM
(
SELECT
telep.tnevi || " - " || szavf.sorsz AS valasztokorzet,
szavf.valtip AS szavazat_tipus,
szavf.n AS ervenyes_szavazolapok,
szavf.m AS ervenytelen_szavazolapok,
cast(szavf.m as float) / cast(szavf.m + szavf. n as float) * 100 AS ervenytelen_arany
FROM szavf
JOIN telep ON (szavf.maz = telep.maz AND szavf.taz = telep.taz)
WHERE szavf.valtip = 'L'
) AS ervenytelen_listas
JOIN
(
SELECT
telep.tnevi || " - " || szavf.sorsz AS valasztokorzet,
szavf.valtip AS szavazat_tipus,
szavf.n AS ervenyes_szavazolapok,
szavf.m AS ervenytelen_szavazolapok,
cast(szavf.m as float) / cast(szavf.m + szavf. n as float) * 100 AS ervenytelen_arany
FROM szavf
JOIN telep ON (szavf.maz = telep.maz AND szavf.taz = telep.taz)
WHERE szavf.valtip = 'J'
) AS ervenytelen_egyeni ON (ervenytelen_listas.valasztokorzet = ervenytelen_egyeni.valasztokorzet)
ORDER BY
ABS(ervenytelen_szavazolapok_diff) DESC
LIMIT 100
; | true |
19c30c0032f0ea5365375da39617d675d839987c | SQL | radtek/abs3 | /sql/mmfo/bars/Table/cck_ob22.sql | WINDOWS-1251 | 7,733 | 2.90625 | 3 | [] | no_license |
PROMPT =====================================================================================
PROMPT *** Run *** ========== Scripts /Sql/BARS/Table/CCK_OB22.sql =========*** Run *** ====
PROMPT =====================================================================================
PROMPT *** ALTER_POLICY_INFO to CCK_OB22 ***
BEGIN
execute immediate
'begin
bpa.alter_policy_info(''CCK_OB22'', ''FILIAL'' , null, null, null, null);
bpa.alter_policy_info(''CCK_OB22'', ''WHOLE'' , null, null, null, null);
null;
end;
';
END;
/
PROMPT *** Create table CCK_OB22 ***
begin
execute immediate '
CREATE TABLE BARS.CCK_OB22
( NBS CHAR(4),
OB22 CHAR(2),
SPI CHAR(2),
SDI CHAR(2),
SP CHAR(2),
SN CHAR(2),
SPN CHAR(2),
SLN CHAR(2),
SD_N CHAR(2),
SD_I CHAR(2),
SD_M CHAR(2),
SD_J CHAR(2),
S903 CHAR(2),
S950 VARCHAR2(8),
S952 CHAR(2),
CR9 CHAR(2),
ACCREZ CHAR(4),
SREZ CHAR(2),
ACC77 CHAR(4),
S77 CHAR(2),
ACC77R CHAR(4),
S77R CHAR(2),
S9N VARCHAR2(8),
SL VARCHAR2(8),
S9601 VARCHAR2(8),
S9611 VARCHAR2(8),
CRD VARCHAR2(8),
SG CHAR(2),
SK0 CHAR(2),
SK9 CHAR(2),
SPN_31 CHAR(2),
SPN_61 CHAR(2),
SPN_181 CHAR(2),
SK9_31 CHAR(2),
SK9_61 CHAR(2),
SK9_181 CHAR(2),
SLK CHAR(2),
SD_9129 CHAR(2),
SD_SK0 CHAR(2),
SD_SK4 CHAR(2),
S260 CHAR(2),
ISG CHAR(2),
S36 CHAR(2),
SD8 CHAR(2),
PSTART VARCHAR2(50),
PFINIS VARCHAR2(50),
D_CLOSE DATE
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
NOCOMPRESS LOGGING
TABLESPACE BRSDYND ';
exception when others then
if sqlcode=-955 then null; else raise; end if;
end;
/
PROMPT *** ALTER_POLICIES to CCK_OB22 ***
exec bpa.alter_policies('CCK_OB22');
COMMENT ON TABLE BARS.CCK_OB22 IS ' 22 ';
COMMENT ON COLUMN BARS.CCK_OB22.D_CLOSE IS ' ';
COMMENT ON COLUMN BARS.CCK_OB22.NBS IS ' ~~';
COMMENT ON COLUMN BARS.CCK_OB22.OB22 IS 'ob22~~';
COMMENT ON COLUMN BARS.CCK_OB22.SPI IS 'ob22~~***5';
COMMENT ON COLUMN BARS.CCK_OB22.SDI IS 'ob22~~***6';
COMMENT ON COLUMN BARS.CCK_OB22.SP IS 'ob22~~***7';
COMMENT ON COLUMN BARS.CCK_OB22.SN IS 'ob22~.% ~***8';
COMMENT ON COLUMN BARS.CCK_OB22.SPN IS 'ob22~%~***9';
COMMENT ON COLUMN BARS.CCK_OB22.SLN IS 'ob22~.%~***?';
COMMENT ON COLUMN BARS.CCK_OB22.SD_N IS 'ob22~% ~6***';
COMMENT ON COLUMN BARS.CCK_OB22.SD_I IS 'ob22~% i~6***';
COMMENT ON COLUMN BARS.CCK_OB22.SD_M IS 'ob22~ ~6***';
COMMENT ON COLUMN BARS.CCK_OB22.SD_J IS 'ob22~ i~6***';
COMMENT ON COLUMN BARS.CCK_OB22.S903 IS 'ob22~~903*';
COMMENT ON COLUMN BARS.CCK_OB22.S950 IS 'ob22~~950*';
COMMENT ON COLUMN BARS.CCK_OB22.S952 IS 'ob22~~952*';
COMMENT ON COLUMN BARS.CCK_OB22.CR9 IS 'ob22~~9129';
COMMENT ON COLUMN BARS.CCK_OB22.ACCREZ IS '';
COMMENT ON COLUMN BARS.CCK_OB22.SREZ IS '';
COMMENT ON COLUMN BARS.CCK_OB22.ACC77 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.S77 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.ACC77R IS '';
COMMENT ON COLUMN BARS.CCK_OB22.S77R IS '';
COMMENT ON COLUMN BARS.CCK_OB22.S9N IS '';
COMMENT ON COLUMN BARS.CCK_OB22.SL IS '';
COMMENT ON COLUMN BARS.CCK_OB22.S9601 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.S9611 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.CRD IS '';
COMMENT ON COLUMN BARS.CCK_OB22.SG IS '';
COMMENT ON COLUMN BARS.CCK_OB22.SK0 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.SK9 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.SPN_31 IS 'ob22~SPN~%~>30 ';
COMMENT ON COLUMN BARS.CCK_OB22.SPN_61 IS 'ob22~SPN~%~>60 ';
COMMENT ON COLUMN BARS.CCK_OB22.SPN_181 IS 'ob22~SPN~%~>180 ';
COMMENT ON COLUMN BARS.CCK_OB22.SK9_31 IS 'ob22~SK9~K~>30 ';
COMMENT ON COLUMN BARS.CCK_OB22.SK9_61 IS 'ob22~SK9~K~>60 ';
COMMENT ON COLUMN BARS.CCK_OB22.SK9_181 IS 'ob22~SK9~K~>180 ';
COMMENT ON COLUMN BARS.CCK_OB22.SLK IS 'ob22~SLK~.';
COMMENT ON COLUMN BARS.CCK_OB22.SD_9129 IS 'OB22~ . i ~ ii~ 9129';
COMMENT ON COLUMN BARS.CCK_OB22.SD_SK0 IS 'OB22~ . i ~ i ~ii';
COMMENT ON COLUMN BARS.CCK_OB22.SD_SK4 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.S260 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.ISG IS 'ob22~ISG~ ';
COMMENT ON COLUMN BARS.CCK_OB22.S36 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.SD8 IS '';
COMMENT ON COLUMN BARS.CCK_OB22.PSTART IS ' .-. ';
COMMENT ON COLUMN BARS.CCK_OB22.PFINIS IS ' .-. (job) ';
PROMPT *** Create constraint XPK_CCKOB22 ***
begin
execute immediate '
ALTER TABLE BARS.CCK_OB22 ADD CONSTRAINT XPK_CCKOB22 PRIMARY KEY (NBS, OB22)
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
TABLESPACE BRSDYNI ENABLE';
exception when others then
if sqlcode=-2260 or sqlcode=-2261 or sqlcode=-2264 or sqlcode=-2275 or sqlcode=-1442 then null; else raise; end if;
end;
/
PROMPT *** Create index XPK_CCKOB22 ***
begin
execute immediate '
CREATE UNIQUE INDEX BARS.XPK_CCKOB22 ON BARS.CCK_OB22 (NBS, OB22)
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
TABLESPACE BRSDYNI ';
exception when others then
if sqlcode=-955 then null; else raise; end if;
end;
/
begin EXECUTE IMMEDIATE 'alter table bars.cck_ob22 add ( K9 int ) ';
exception when others then if SQLCODE = -01430 then null; else raise; end if; -- ORA-01430: column being added already exists in table
end;
/
COMMENT ON COLUMN BARS.CCK_OB22.K9 IS ' IFRS= -9 ("")';
begin EXECUTE IMMEDIATE 'alter table bars.cck_ob22 add ( KL1 int ) ';
exception when others then if SQLCODE = -01430 then null; else raise; end if; -- ORA-01430: column being added already exists in table
end;
/
COMMENT ON COLUMN BARS.CCK_OB22.KL1 IS ' ';
begin EXECUTE IMMEDIATE 'alter table bars.cck_ob22 add ( SNA char(6) ) ';
exception when others then if SQLCODE = -01430 then null; else raise; end if; -- ORA-01430: column being added already exists in table
end;
/
PROMPT *** Create grants CCK_OB22 ***
grant DELETE,FLASHBACK,INSERT,SELECT,UPDATE on CCK_OB22 to BARS_ACCESS_DEFROLE;
grant SELECT on CCK_OB22 to BARS_DM;
grant DELETE,INSERT,SELECT,UPDATE on CCK_OB22 to RCC_DEAL;
grant SELECT on CCK_OB22 to UPLD;
grant DELETE,FLASHBACK,INSERT,SELECT,UPDATE on CCK_OB22 to WR_ALL_RIGHTS;
grant FLASHBACK,SELECT on CCK_OB22 to WR_REFREAD;
PROMPT =====================================================================================
PROMPT *** End *** ========== Scripts /Sql/BARS/Table/CCK_OB22.sql =========*** End *** ====
PROMPT =====================================================================================
| true |
3874362e0054965d4155ae7c18ef3f887baf179c | SQL | ahueteg/Datamart-MKT | /Lab SQL/VISTAS/VISTA GLP SELLOUT.sql | ISO-8859-10 | 3,148 | 3.609375 | 4 | [] | no_license |
/*demo*/
SELECT
A.Fecha,
A.GrpID GrupoID,
B.CadenaID,
C.OficinaID,
D.Grupo1ID GrupoTratID,
F.SupervisorID,
E.VendedorID,
NULL UbigeoID,
H.ProPstID,
J.PdvID,
I.PrecioID,
A.UnidDesp,
A.MontoDespCliente,
A.UnidDesp*I.PrecioLista MontoDesp
FROM per.GLP_SELLOUT A
LEFT JOIN per.MAESTRO_CADENA B
ON A.CadenaIDClie=B.CadenaIDClie AND A.GrpID=B.GrpID
LEFT JOIN per.MAESTRO_OFICINA C
ON A.OficinaIDClie=C.OficinaIDClie AND A.GrpID=C.GrpID
LEFT JOIN per.MAESTRO_GRUPO1 D
ON A.GrupoTratIDClie=D.Grupo1IDClie AND A.GrpID=D.GrpID
LEFT JOIN per.MAESTRO_VENDEDOR E
ON A.VendedorIDClie=E.VendedorIDClie AND A.GrpID=E.GrpID
LEFT JOIN per.MAESTRO_SUPERVISOR F
ON A.SupervisorIDClie=F.SupervisorIDClie AND A.GrpID=F.GrpID
LEFT JOIN per.MAESTRO_TIEMPO G
ON A.Fecha=G.Fecha
LEFT JOIN per.MAESTRO_PRODUCTO_FUENTE H
ON A.ProIDClie=H.ProIDClie AND A.GrpID=H.GrpID
LEFT JOIN per.MAESTRO_PRODUCTO_PRECIO I
ON G.AoSemana_GL=I.AoSemana_GL AND H.ProPstID=I.ProPstID AND A.GrpID=I.GrpID
LEFT JOIN per.MAESTRO_PDV J
ON A.PdvIDClie=J.PdvIDClie AND A.GrpID=J.GrpID
/*VISTA DISTRIBUTIVO*/
DROP VIEW per.[1:Informacion]
CREATE VIEW per.[1:Informacion]
AS
SELECT
substring(A.[Fecha],7,2)+'/'+SUBSTRING(A.fecha,5,2)+'/'+SUBSTRING(A.fecha,1,4) Fecha,
A.GrpID GrupoID,
B.CadenaID,
C.OficinaID,
D.Grupo1ID GrupoTratID,
F.SupervisorID,
E.VendedorID,
NULL UbigeoID,
J.PdvID,
H.ProPstID,
I.PrecioID,
A.UnidDesp,
A.UnidExist,
A.UnidCedis,
A.UnidTrans,
A.MontoDespCliente,
A.UnidDesp*I.PVP MontoDespPvp,
A.UnidDesp*I.PrecioLista MontoDesp,
A.UnidExist*I.PrecioLista MontoExist,
A.UnidCedis*I.PrecioLista MontoCedis,
A.UnidTrans*I.PrecioLista MontoTrans
FROM
(
SELECT
A.Fecha,
A.GrpID,
A.CadenaIDClie,
A.OficinaIDClie,
A.GrupoTratIDClie,
A.VendedorIDClie,
A.SupervisorIDClie,
A.ProIDClie,
A.PdvIDClie,
A.UnidDesp,
B.UnidExist,
B.UnidCedis,
B.UnidTrans,
A.MontoDespCliente
FROM PER.GLP_SELLOUT A
LEFT JOIN
(
SELECT * FROM
PER.GLP_STOCK
WHERE 1=2) B
ON A.ProIDClie=B.ProIDClie
UNION ALL
SELECT
B.Fecha,
B.GrpID,
B.CadenaIDClie,
A.OficinaIDClie,
A.GrupoTratIDClie,
A.VendedorIDClie,
A.SupervisorIDClie,
B.ProIDClie,
A.PdvIDClie,
A.UnidDesp,
B.UnidExist,
B.UnidCedis,
B.UnidTrans,
A.MontoDespCliente
FROM PER.GLP_STOCK B
LEFT JOIN
(
SELECT * FROM
PER.GLP_SELLOUT
WHERE 1=2) A
ON A.ProIDClie=B.ProIDClie
) A
LEFT JOIN per.MAESTRO_CADENA B
ON A.CadenaIDClie=B.CadenaIDClie AND A.GrpID=B.GrpID
LEFT JOIN per.MAESTRO_OFICINA C
ON A.OficinaIDClie=C.OficinaIDClie AND A.GrpID=C.GrpID
LEFT JOIN per.MAESTRO_GRUPO1 D
ON A.GrupoTratIDClie=D.Grupo1IDClie AND A.GrpID=D.GrpID
LEFT JOIN per.MAESTRO_VENDEDOR E
ON A.VendedorIDClie=E.VendedorIDClie AND A.GrpID=E.GrpID
LEFT JOIN per.MAESTRO_SUPERVISOR F
ON A.SupervisorIDClie=F.SupervisorIDClie AND A.GrpID=F.GrpID
LEFT JOIN per.MAESTRO_TIEMPO G
ON A.Fecha=G.Fecha
LEFT JOIN per.MAESTRO_PRODUCTO_FUENTE H
ON A.ProIDClie=H.ProIDClie AND A.GrpID=H.GrpID
LEFT JOIN per.MAESTRO_PRODUCTO_PRECIO I
ON G.AoSemana_GL=I.AoSemana_GL AND H.ProPstID=I.ProPstID AND A.GrpID=I.GrpID
LEFT JOIN per.MAESTRO_PDV J
ON A.PdvIDClie=J.PdvIDClie AND A.GrpID=J.GrpID
WHERE A.Fecha>'20131230'
SELECT COUNT(1) FROM PER.[1:Informacion] | true |
6699fc93f50c5be9303af2e8ba856884a0d649c8 | SQL | cms-sw/hlt-confdb | /sql/revoke_restore_privileges_procedures_ORACLE.sql | UTF-8 | 4,820 | 3.765625 | 4 | [] | no_license | ---------------------------------------------------------------------------------
--- CREATOR: Raul Jimenez Estupinan <raul.jimenez.estupinan@cern.ch>
--- DATE: 2011-12-16
--- FILE: revoke_restore_privileges_procedures_ORACLE.sql
---------------------------------------------------------------------------------
-- SET SERVEROUTPUT ON;
---------------------------------------------------------------------------------
-- TEMPORARY TABLE TO STORE TABLE'S PRIVILEGES:
-- NOTE: 'on commit preserve rows' holds on to the data until the session ends.
---------------------------------------------------------------------------------
CREATE GLOBAL TEMPORARY TABLE temp_stored_privileges
(
TABLE_NAME VARCHAR2(512),
GRANTEE VARCHAR2(512),
PRIVILEGE VARCHAR2(512)
) ON COMMIT PRESERVE ROWS;
---------------------------------------------------------------------------------
-- StoreAndRevokePrivileges
-- Stores previously granted privileges for all the users of one particular
-- table, into the table 'temp_stored_privileges'.
---------------------------------------------------------------------------------
CREATE OR REPLACE Procedure StoreAndRevokePrivileges (tableName IN varchar2)
IS
Exist NUMBER;
v_table_name VARCHAR2(512);
v_grantee VARCHAR2(512);
v_privilege VARCHAR2(512);
sql_statement VARCHAR2(1024);
/* store privileges cursor: */
CURSOR cur_privileges IS
SELECT table_name ,
grantee ,
privilege
FROM user_tab_privs
WHERE table_name = tableName;
/* store privileges cursor: */
CURSOR cur_revoke IS
SELECT table_name ,
grantee ,
privilege
FROM temp_stored_privileges;
BEGIN
Select count(*) into Exist from all_tab_columns
where table_name = tableName;
if(Exist = 0) then
DBMS_OUTPUT.PUT_LINE('TABLE ' || tableName || ' DOES NOT EXIST');
return;
end if;
DBMS_OUTPUT.PUT_LINE('[StoreAndRevokePrivileges] Storing table privileges for table ' || tableName);
execute immediate 'DELETE FROM temp_stored_privileges';
/* load privileges: */
OPEN cur_privileges;
LOOP
FETCH cur_privileges
INTO v_table_name,v_grantee,v_privilege;
EXIT WHEN cur_privileges%NOTFOUND;
INSERT INTO temp_stored_privileges VALUES(v_table_name, v_grantee, v_privilege);
END LOOP;
CLOSE cur_privileges;
DBMS_OUTPUT.PUT_LINE('[StoreAndRevokePrivileges] Revoking privileges for table ' || tableName);
/* revoke privileges: */
OPEN cur_revoke;
LOOP
FETCH cur_revoke
INTO v_table_name,v_grantee,v_privilege;
EXIT WHEN cur_revoke%NOTFOUND;
sql_statement:= 'REVOKE ' || v_privilege || ' ON ' || v_table_name || ' FROM ' || v_grantee;
DBMS_OUTPUT.PUT_LINE('[StoreAndRevokePrivileges] '|| sql_statement);
execute immediate sql_statement;
END LOOP;
CLOSE cur_revoke;
DBMS_OUTPUT.PUT_LINE('[StoreAndRevokePrivileges] Privileges for ' || tableName || ' have been stored in table ''temp_stored_privileges''');
END;
/
---------------------------------------------------------------------------------
-- LoadAndGrantPrivileges
-- Restores previously revoked privileges by StoreAndRevokePrivileges, using the
-- table 'temp_stored_privileges'.
---------------------------------------------------------------------------------
CREATE OR REPLACE Procedure LoadAndGrantPrivileges (tableName IN varchar2)
IS
Exist NUMBER;
v_table_name VARCHAR2(512);
v_grantee VARCHAR2(512);
v_privilege VARCHAR2(512);
sql_statement VARCHAR2(1024);
/* store privileges cursor: */
CURSOR cur_grant IS
SELECT table_name ,
grantee ,
privilege
FROM temp_stored_privileges;
BEGIN
Select count(*) into Exist from all_tab_columns
where table_name = tableName;
if(Exist = 0) then
DBMS_OUTPUT.PUT_LINE('TABLE ' || tableName || ' DOES NOT EXIST');
return;
end if;
DBMS_OUTPUT.PUT_LINE('[LoadAndGrantPrivileges] Grantting privileges for ' || tableName );
/* grant privileges: */
OPEN cur_grant;
LOOP
FETCH cur_grant
INTO v_table_name,v_grantee,v_privilege;
EXIT WHEN cur_grant%NOTFOUND;
sql_statement:= 'GRANT ' || v_privilege || ' ON ' || v_table_name || ' TO ' || v_grantee;
DBMS_OUTPUT.PUT_LINE('[LoadAndGrantPrivileges] '|| sql_statement);
execute immediate sql_statement;
END LOOP;
CLOSE cur_grant;
DBMS_OUTPUT.PUT_LINE('[LoadAndGrantPrivileges] Privileges for ' || tableName || ' have been restored');
END;
/
COMMIT;
| true |
c88daf30eb0d8564f17b8c2b940c43b78ce55ac4 | SQL | mseong123/protocount-nodejs-mysql | /mysql_files/STORED PROCEDURES/PURCHASE_DEBIT_NOTE/SELECT_PURCHASE_DEBIT_NOTE.sql | UTF-8 | 1,057 | 3.546875 | 4 | [] | no_license |
DELIMITER //
CREATE PROCEDURE SELECT_PURCHASE_DEBIT_NOTE(IN PURCHASE_DEBIT_NOTE_NUM_PARAM VARCHAR(50))
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
SELECT CREDITOR_NUM, CREDITOR_NAME, CREDITOR_ADDRESS,PURCHASE_DEBIT_NOTE_NUM,PURCHASE_DEBIT_NOTE_DATE,PURCHASE_DEBIT_NOTE_DESC,PURCHASE_DEBIT_NOTE_CREDIT_TERM, purchase_debit_note.GL_ACC_NUM, PURCHASE_DEBIT_NOTE_NUM AS PURCHASE_DEBIT_NOTE_NUM_OLD FROM creditor JOIN purchase_debit_note USING (CREDITOR_NUM) WHERE PURCHASE_DEBIT_NOTE_NUM=PURCHASE_DEBIT_NOTE_NUM_PARAM;
SELECT PURCHASE_DEBIT_NOTELINE_LINENUMBER,PURCHASE_DEBIT_NOTELINE_STOCK_NUM,PURCHASE_DEBIT_NOTELINE_STOCK_DESC,PURCHASE_DEBIT_NOTELINE_STOCK_PRICE,PURCHASE_DEBIT_NOTELINE_STOCK_QTY,PURCHASE_DEBIT_NOTELINE_DISCOUNT FROM purchase_debit_noteline WHERE PURCHASE_DEBIT_NOTE_NUM=PURCHASE_DEBIT_NOTE_NUM_PARAM;
SELECT PURCHASE_DEBIT_NOTELINE_LINENUMBER,STOCK_NUM,PURCHASE_DEBIT_NOTE_STOCK_QTY FROM purchase_debit_note_stock WHERE PURCHASE_DEBIT_NOTE_NUM=PURCHASE_DEBIT_NOTE_NUM_PARAM;
COMMIT;
END// | true |
eb1c8f7c20608eef7e29b9d4678157b66633b6a3 | SQL | VuDinh/SA | /javafxtest/out/production/javafxtest/Controllers/Server/accounts.sql | UTF-8 | 2,029 | 2.734375 | 3 | [] | no_license | drop table if exists accounts;
drop table if exists heroBeginPositions;
drop table if exists monsterBeginPositions;
drop table if exists monsterPositions;
create table accounts(
username text primary key,
password text
);
insert into accounts(username,password) values('long','123');
insert into accounts(username,password) values('dinh','123');
insert into accounts(username,password) values('hung','123');
insert into accounts(username,password) values('quan','123');
create table heroBeginPositions(
id integer primary key,
row integer,
col integer
);
insert into heroBeginPositions(id,row,col) values(0,37,1);
insert into heroBeginPositions(id,row,col) values(1,38,1);
insert into heroBeginPositions(id,row,col) values(2,39,1);
insert into heroBeginPositions(id,row,col) values(3,38,0);
insert into heroBeginPositions(id,row,col) values(4,38,2);
insert into heroBeginPositions(id,row,col) values(5,0,38);
insert into heroBeginPositions(id,row,col) values(6,1,38);
insert into heroBeginPositions(id,row,col) values(7,2,38);
insert into heroBeginPositions(id,row,col) values(8,1,37);
insert into heroBeginPositions(id,row,col) values(9,1,39);
create table monsterPositions(
id integer primary key,
row integer,
col integer
);
--insert into monsterPositions(id,row,col) values(0,13,8);
insert into monsterPositions(id,row,col) values(0,37,4);
insert into monsterPositions(id,row,col) values(1,9,14);
insert into monsterPositions(id,row,col) values(2,19,14);
insert into monsterPositions(id,row,col) values(3,26,8);
insert into monsterPositions(id,row,col) values(4,25,20);
insert into monsterPositions(id,row,col) values(5,30,14);
insert into monsterPositions(id,row,col) values(6,30,25);
insert into monsterPositions(id,row,col) values(7,26,31);
insert into monsterPositions(id,row,col) values(8,20,25);
insert into monsterPositions(id,row,col) values(9,14,19);
insert into monsterPositions(id,row,col) values(10,9,25);
insert into monsterPositions(id,row,col) values(11,14,31);
| true |
0fcc0d83dc64686c5db6adf53e6e99ee298c536c | SQL | ProgressoRU/students | /protected/sql/students.sql | UTF-8 | 4,536 | 3.546875 | 4 | [] | no_license | /*
Navicat MySQL Data Transfer
Source Server : MySql
Source Server Version : 50523
Source Host : localhost:3306
Source Database : students
Target Server Type : MYSQL
Target Server Version : 50523
File Encoding : 65001
Date: 2015-05-06 23:25:31
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for attachments
-- ----------------------------
DROP TABLE IF EXISTS `attachments`;
CREATE TABLE `attachments` (
`attach_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`lecture_id` int(11) unsigned NOT NULL,
`url` varchar(255) DEFAULT NULL,
`type` varchar(5) DEFAULT NULL,
`title` varchar(100) NOT NULL,
`description` varchar(255) DEFAULT NULL,
`date_created` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`attach_id`),
KEY `artID` (`lecture_id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for disciplines
-- ----------------------------
DROP TABLE IF EXISTS `disciplines`;
CREATE TABLE `disciplines` (
`discipline_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(64) NOT NULL,
`description` varchar(144) DEFAULT NULL,
`creator_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`discipline_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for groups
-- ----------------------------
DROP TABLE IF EXISTS `groups`;
CREATE TABLE `groups` (
`group_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`passcode` char(16) NOT NULL,
`expire_date` timestamp NULL DEFAULT NULL,
`teacher_id` int(11) unsigned DEFAULT NULL,
`title` varchar(16) NOT NULL,
PRIMARY KEY (`group_id`),
UNIQUE KEY `passcode` (`passcode`) USING HASH
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for group_access
-- ----------------------------
DROP TABLE IF EXISTS `group_access`;
CREATE TABLE `group_access` (
`group_id` int(11) unsigned NOT NULL,
`discipline_id` int(11) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for group_progress
-- ----------------------------
DROP TABLE IF EXISTS `group_progress`;
CREATE TABLE `group_progress` (
`group_id` int(11) unsigned NOT NULL,
`lecture_id` int(11) unsigned NOT NULL,
`date_deadline` timestamp NULL DEFAULT NULL,
`is_visible` tinyint(1) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for lectures
-- ----------------------------
DROP TABLE IF EXISTS `lectures`;
CREATE TABLE `lectures` (
`lecture_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(80) NOT NULL,
`description` longtext NOT NULL,
`date_created` timestamp NULL DEFAULT NULL,
`date_updated` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`discipline_id` int(4) unsigned DEFAULT NULL,
PRIMARY KEY (`lecture_id`),
KEY `intClass` (`discipline_id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for news
-- ----------------------------
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
`news_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`news` longtext NOT NULL,
`importance` tinyint(4) unsigned NOT NULL,
`date_created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`news_id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for subscriptions
-- ----------------------------
DROP TABLE IF EXISTS `subscriptions`;
CREATE TABLE `subscriptions` (
`user_id` int(11) unsigned NOT NULL,
`group_id` int(11) unsigned NOT NULL,
`is_editor` tinyint(1) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(16) NOT NULL,
`pass_hash` varchar(255) DEFAULT NULL,
`surname` varchar(42) DEFAULT NULL,
`name` varchar(42) DEFAULT NULL,
`patronymic` varchar(42) DEFAULT NULL COMMENT 'Отчество',
`session_hash` varchar(32) DEFAULT NULL,
`last_ip` varchar(16) DEFAULT NULL,
`role` varchar(8) NOT NULL,
`useragent` varchar(255) DEFAULT NULL,
`group` varchar(12) NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
| true |
8b84f4f94c0a5644826c55e561809c5d2fb5b36e | SQL | nttv/C1120G1-NguyenThiTuongVi | /Module-3/session_2/banking_db.sql | UTF-8 | 1,354 | 4.09375 | 4 | [] | no_license | create database ss2_banking_db;
use ss2_banking_db;
CREATE TABLE customers (
customer_number INT AUTO_INCREMENT PRIMARY KEY,
fullname VARCHAR(100) NOT NULL,
address VARCHAR(255),
email VARCHAR(100) NOT NULL,
phone VARCHAR(20) NOT NULL
);
CREATE TABLE accounts (
account_number INT AUTO_INCREMENT PRIMARY KEY,
account_type VARCHAR(20) NOT NULL,
date DATE NOT NULL,
balance INT NOT NULL,
customer_number INT UNIQUE NOT NULL,
FOREIGN KEY (customer_number)
REFERENCES customers (customer_number),
CHECK (account_type IN ('vip' , 'thuong', 'doanh nghiep'))
);
CREATE TABLE transactions (
tran_number INT AUTO_INCREMENT PRIMARY KEY,
account_number INT NOT NULL,
date DATE NOT NULL,
amounts INT NOT NULL,
descriptions VARCHAR(255),
FOREIGN KEY (account_number)
REFERENCES accounts (account_number)
);
insert into customers (fullname, address, email, phone)
values
("NVA", "Da Nang", "abc@abc.abc", "0909000999"),
("NVB", null, "abc@abc.abc", "0909000999");
select * from customers;
delete from customers;
alter table customers auto_increment = 1;
insert into accounts (account_type, date, balance, customer_number)
values
("vip", "2020-01-01", 1000, 1),
("thuong", "2021-01-01", 0, 2);
select * from accounts;
delete from accounts;
alter table customers auto_increment = 1; | true |
a73e3f79881916a1416c7ace83c5233842cbc98b | SQL | caioRafael/projetoOficina | /MecanicaGomesAtualizado09_01.sql | UTF-8 | 3,058 | 3.484375 | 3 | [] | no_license | create database MecanicaGomes;
use MecanicaGomes;
create table cliente(
id_cliente integer auto_increment,
nome varchar(60),
email varchar(45) not null,
senha varchar(45) not null,
endereco varchar(60),
telefone varchar(45),
primary key(id_cliente)
);
insert into cliente( nome, email,senha,endereco,telefone)
values('Irlan','irlan@gmail.com','1234', 'Rua A', 'xx - xxxxx - xxxx');
create table peca(
id_peca integer auto_increment,
nome varchar(60),
preco varchar(45),
estoque varchar(45),
imagem varchar(60),
primary key(id_peca)
);
insert into peca( nome, preco, estoque,imagem)
values('Catraca de freio','120', '10','images/catracaDeFreio.png'),
('Feixe de Mola','70', '30','images/feixeDeMola.jpg'),('Juntas de Cabecote','120', '15','images/juntas.jpg'),
('Bracadeira','120', '15','images/brassadeira.jpg'),('Cuica de Freio','250', '15','images/cuicaDeFreio.jpg'),
('Farol','120', '15','images/farol.jpg'),
('Lona de Freio','120', '15','images/lonaDeFreio.jpg'),('Maneco','120', '15','images/maneco.jpg'),
('Parafuso de Centro','120', '15','images/ParafusoCentro.jpg'),('Pastilha de freio','120', '15','images/pastilha-de-freio.jpg'),
('Reparo de valvula','120', '15','images/reparoValvula.jpg'),('Cinematico do Rodoar','90', '15','images/Cinematico-do-Rodoar.jpg');
create table peca_cliente(
id_peca_cliente integer auto_increment,
id_cliente_fk integer,
id_peca_fk integer,
data_compra varchar(45),
primary key(id_peca_cliente),
foreign key(id_cliente_fk) references cliente(id_cliente),
foreign key(id_peca_fk) references peca(id_peca)
);
create table pagamento(
id_pagamento integer not null,
tipo varchar(60),
primary key(id_pagamento)
);
create table cliente_pagamento(
id_cliente_pag integer auto_increment,
id_pagamento_fk integer,
id_cliente_fk integer,
valor_total varchar(45),
primary key(id_cliente_pag),
foreign key(id_cliente_fk) references cliente(id_cliente),
foreign key(id_pagamento_fk) references pagamento(id_pagamento)
);
create table servico(
id_servico integer auto_increment,
preco varchar(45),
tipo varchar(60),
primary key(id_servico)
);
create table funcionario(
id_funcionario integer not null auto_increment,
telefone varchar(45),
endereco varchar(60),
nome varchar(60),
salario varchar(45),
senha varchar(45),
primary key(id_funcionario)
);
create table servico_funcionario(
id_serv_func integer auto_increment ,
id_servico_fk integer,
id_funcionario_fk integer,
id_cliente_fk integer,
data_inicio varchar(45),
data_fim varchar(45),
primary key(id_serv_func),
foreign key(id_servico_fk) references servico(id_servico),
foreign key(id_funcionario_fk) references funcionario(id_funcionario),
foreign key(id_cliente_fk) references cliente(id_cliente)
);
create table contato (
id integer primary key auto_increment,
nome varchar(45),
email varchar(45),
endereco varchar(45),
descricao varchar(45),
data_servico varchar(45)
); | true |
9726aba02cb1424d6971b05401f391eab19c13cb | SQL | LEO-DAC/tecnologiasYaplicacionesWeb | /trabajo en clase/practica07/practica07_final_.sql | UTF-8 | 6,457 | 2.859375 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Servidor: localhost
-- Tiempo de generación: 05-06-2019 a las 02:51:42
-- Versión del servidor: 10.1.40-MariaDB
-- Versión de PHP: 7.3.5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `practica07_final_`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `alumno`
--
CREATE TABLE `alumno` (
`matricula` int(7) NOT NULL,
`nombres` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`apellidos` varchar(30) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Volcado de datos para la tabla `alumno`
--
INSERT INTO `alumno` (`matricula`, `nombres`, `apellidos`) VALUES
(1410004, 'Carlos Alberto', 'Alarcon Longoria'),
(1530438, 'Leonardo Daniel', 'Alonso Cepeda');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `grupo`
--
CREATE TABLE `grupo` (
`id` int(11) NOT NULL,
`carrera` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`cuatrimestre` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Volcado de datos para la tabla `grupo`
--
INSERT INTO `grupo` (`id`, `carrera`, `cuatrimestre`) VALUES
(5, 'Licenciatura en Administración y Gestión empresarial', 7),
(6, 'IngenierÃa en tecnologÃas de Manufactura', 3),
(7, 'IngenierÃa en sistemas automotrices', 8),
(8, 'Ingenieria en tecnologÃas de la información', 9);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `grupo_materia`
--
CREATE TABLE `grupo_materia` (
`id_grupo` int(11) NOT NULL,
`id_materia` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Volcado de datos para la tabla `grupo_materia`
--
INSERT INTO `grupo_materia` (`id_grupo`, `id_materia`) VALUES
(5, 4),
(6, 4),
(6, 6),
(7, 5),
(8, 4);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `materia`
--
CREATE TABLE `materia` (
`id` int(11) NOT NULL,
`nombre` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`clave` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`carrera` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`id_profesor` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Volcado de datos para la tabla `materia`
--
INSERT INTO `materia` (`id`, `nombre`, `clave`, `carrera`, `id_profesor`) VALUES
(4, 'TECNOLOGÃA Y APLICACIONES WEB', '1478', 'IngenierÃa en tecnologÃas de la información', 4),
(5, 'programación estructurada', '4865', 'IngenierÃa en tecnologÃas de la información', 3),
(6, 'Aplicaciones moviles', '7865', 'IngenierÃa en tecnologÃas de la información', 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `materia_alumno`
--
CREATE TABLE `materia_alumno` (
`id_materia` int(11) NOT NULL,
`id_alumno` int(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Volcado de datos para la tabla `materia_alumno`
--
INSERT INTO `materia_alumno` (`id_materia`, `id_alumno`) VALUES
(4, 1530438),
(5, 1530438);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `profesor`
--
CREATE TABLE `profesor` (
`id` int(11) NOT NULL,
`nombres` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`apellidos` varchar(30) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Volcado de datos para la tabla `profesor`
--
INSERT INTO `profesor` (`id`, `nombres`, `apellidos`) VALUES
(1, 'Marco Aurelio', 'Nuño maganda'),
(3, 'Jorgue Arturo', 'Hernandez Almazan'),
(4, 'Luis Roberto', 'Flores'),
(5, 'MARIO HUMBERTO', ' RODRIGUEZ CHÃVEZ');
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `alumno`
--
ALTER TABLE `alumno`
ADD PRIMARY KEY (`matricula`),
ADD UNIQUE KEY `matricula` (`matricula`);
--
-- Indices de la tabla `grupo`
--
ALTER TABLE `grupo`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `grupo_materia`
--
ALTER TABLE `grupo_materia`
ADD PRIMARY KEY (`id_grupo`,`id_materia`),
ADD KEY `id_grupo` (`id_grupo`,`id_materia`),
ADD KEY `id_materia` (`id_materia`);
--
-- Indices de la tabla `materia`
--
ALTER TABLE `materia`
ADD PRIMARY KEY (`id`),
ADD KEY `id_profesor` (`id_profesor`);
--
-- Indices de la tabla `materia_alumno`
--
ALTER TABLE `materia_alumno`
ADD PRIMARY KEY (`id_materia`,`id_alumno`),
ADD UNIQUE KEY `id_materia` (`id_materia`,`id_alumno`),
ADD KEY `id_materia_2` (`id_materia`,`id_alumno`),
ADD KEY `id_alumno` (`id_alumno`);
--
-- Indices de la tabla `profesor`
--
ALTER TABLE `profesor`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `grupo`
--
ALTER TABLE `grupo`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT de la tabla `materia`
--
ALTER TABLE `materia`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT de la tabla `profesor`
--
ALTER TABLE `profesor`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `grupo_materia`
--
ALTER TABLE `grupo_materia`
ADD CONSTRAINT `grupo_materia_ibfk_1` FOREIGN KEY (`id_grupo`) REFERENCES `grupo` (`id`),
ADD CONSTRAINT `grupo_materia_ibfk_2` FOREIGN KEY (`id_materia`) REFERENCES `materia` (`id`);
--
-- Filtros para la tabla `materia`
--
ALTER TABLE `materia`
ADD CONSTRAINT `materia_ibfk_1` FOREIGN KEY (`id_profesor`) REFERENCES `profesor` (`id`);
--
-- Filtros para la tabla `materia_alumno`
--
ALTER TABLE `materia_alumno`
ADD CONSTRAINT `materia_alumno_ibfk_2` FOREIGN KEY (`id_materia`) REFERENCES `materia` (`id`),
ADD CONSTRAINT `materia_alumno_ibfk_3` FOREIGN KEY (`id_alumno`) REFERENCES `alumno` (`matricula`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| true |
ab992e6733aca437f03f13e5cfeb82271a921f65 | SQL | 617961/uni | /it350/IT350-PZ-Aleksandra_Blagojevic_3801/UniversitySystem/unibase.sql | UTF-8 | 14,322 | 3.203125 | 3 | [] | no_license | /*==============================================================*/
/* DBMS name: MySQL 5.0 */
/* Created on: 1/12/2020 7:55:14 PM */
/*==============================================================*/
create database if not exists unibase;
use unibase;
create user 'admin'@'localhost' identified by 'admin';
grant all privileges on unibase to 'admin'@'localhost' identified by 'admin';
drop table if exists curriculum;
drop table if exists degree;
drop table if exists faculty;
drop table if exists grading;
drop table if exists homework;
drop table if exists homework_obligation;
drop table if exists obligation_definition;
drop table if exists person;
drop table if exists professor;
drop table if exists project;
drop table if exists project_obligation;
drop table if exists question;
drop table if exists semester;
drop table if exists student;
drop table if exists study_program;
drop table if exists study_year;
drop table if exists stud_sub;
drop table if exists subject;
drop table if exists subject_definition;
drop table if exists test;
drop table if exists test_obligation;
/*==============================================================*/
/* Table: curriculum */
/*==============================================================*/
create table curriculum
(
curriculum_id int not null auto_increment,
year_id int not null,
semester_id int not null,
program_id int,
primary key (curriculum_id)
);
/*==============================================================*/
/* Table: degree */
/*==============================================================*/
create table degree
(
degree_id int not null auto_increment,
degree_name varchar(64) not null,
primary key (degree_id)
);
/*==============================================================*/
/* Table: faculty */
/*==============================================================*/
create table faculty
(
faculty_id int not null auto_increment,
degree_id int not null,
faculty_name varchar(64) not null,
primary key (faculty_id)
);
/*==============================================================*/
/* Table: grading */
/*==============================================================*/
create table grading
(
grading_id int not null auto_increment,
stud_id int not null,
prof_id int not null,
obli_def_id int,
file_location varchar(256) not null,
date date not null,
points real not null,
days_late smallint not null,
primary key (grading_id)
);
/*==============================================================*/
/* Table: homework */
/*==============================================================*/
create table homework
(
homework_id int not null auto_increment,
homework_num smallint not null,
homework_text text not null,
primary key (homework_id)
);
/*==============================================================*/
/* Table: homework_obligation */
/*==============================================================*/
create table homework_obligation
(
hw_ob_id int not null auto_increment,
homework_id int not null,
prev_sent smallint not null,
primary key (hw_ob_id)
);
/*==============================================================*/
/* Table: obligation_definition */
/*==============================================================*/
create table obligation_definition
(
obli_def_id int not null auto_increment,
hw_ob_id int not null,
proj_ob_id int,
test_ob_id int not null,
sub_def_id int not null,
max_points real not null,
primary key (obli_def_id)
);
/*==============================================================*/
/* Table: person */
/*==============================================================*/
create table person
(
person_id int not null auto_increment,
jmbg varchar(13) not null,
degree_name varchar(64) not null,
surname varchar(64) not null,
phone_number varchar(32) not null,
email varchar(64) not null,
city_of_birth varchar(32) not null,
date_of_birth date not null,
primary key (person_id)
);
/*==============================================================*/
/* Table: professor */
/*==============================================================*/
create table professor
(
person_id int not null auto_increment,
prof_id int not null,
study_title varchar(16) not null,
prof_email varchar(64) not null,
primary key (person_id, prof_id)
);
/*==============================================================*/
/* Table: project */
/*==============================================================*/
create table project
(
project_id int not null auto_increment,
name varchar(128) not null,
abstract text not null,
key_words text not null,
primary key (project_id)
);
/*==============================================================*/
/* Table: project_obligation */
/*==============================================================*/
create table project_obligation
(
proj_ob_id int not null auto_increment,
project_id int not null,
primary key (proj_ob_id)
);
/*==============================================================*/
/* Table: question */
/*==============================================================*/
create table question
(
question_id int not null auto_increment,
ans1 text not null,
ans2 text not null,
ans3 text not null,
correct text not null,
primary key (question_id)
);
/*==============================================================*/
/* Table: semester */
/*==============================================================*/
create table semester
(
semester_id int not null auto_increment,
semester_code smallint not null,
primary key (semester_id)
);
/*==============================================================*/
/* Table: student */
/*==============================================================*/
create table student
(
person_id int not null auto_increment,
stud_id int not null,
study_type varchar(16) not null,
stud_email varchar(64) not null,
primary key (person_id, stud_id)
);
/*==============================================================*/
/* Table: study_program */
/*==============================================================*/
create table study_program
(
program_id int not null auto_increment,
faculty_id int,
study_name varchar(32) not null,
duration smallint not null,
min_espb smallint not null,
study_title varchar(16) not null,
primary key (program_id)
);
/*==============================================================*/
/* Table: study_year */
/*==============================================================*/
create table study_year
(
year_id int not null auto_increment,
yearstart date not null,
yearend date not null,
primary key (year_id)
);
/*==============================================================*/
/* Table: stud_sub */
/*==============================================================*/
create table stud_sub
(
person_id int not null auto_increment,
stud_id int not null,
subject_id int not null,
primary key (person_id, stud_id, subject_id)
);
/*==============================================================*/
/* Table: subject */
/*==============================================================*/
create table subject
(
subject_id int not null auto_increment,
person_id int not null,
prof_id int not null,
subject_code varchar(5) not null,
subject_name varchar(64) not null,
espb smallint not null,
primary key (subject_id)
);
/*==============================================================*/
/* Table: subject_definition */
/*==============================================================*/
create table subject_definition
(
sub_def_id int not null auto_increment,
curriculum_id int not null,
subject_id int not null,
primary key (sub_def_id)
);
/*==============================================================*/
/* Table: test */
/*==============================================================*/
create table test
(
test_id int not null auto_increment,
question_id int not null,
test_num smallint not null,
primary key (test_id)
);
/*==============================================================*/
/* Table: test_obligation */
/*==============================================================*/
create table test_obligation
(
test_ob_id int not null auto_increment,
test_id int not null,
primary key (test_ob_id)
);
alter table curriculum add constraint fk_r3 foreign key (program_id)
references study_program (program_id) on delete restrict on update restrict;
alter table curriculum add constraint fk_r4 foreign key (year_id)
references study_year (year_id) on delete restrict on update restrict;
alter table curriculum add constraint fk_r6 foreign key (semester_id)
references semester (semester_id) on delete restrict on update restrict;
alter table faculty add constraint fk_r1 foreign key (degree_id)
references degree (degree_id) on delete restrict on update restrict;
alter table grading add constraint fk_grading_ob_def foreign key (obli_def_id)
references obligation_definition (obli_def_id) on delete restrict on update restrict;
alter table grading add constraint fk_r17 foreign key (grading_id, stud_id)
references student (person_id, stud_id) on delete restrict on update restrict;
alter table grading add constraint fk_r19 foreign key (grading_id, prof_id)
references professor (person_id, prof_id) on delete restrict on update restrict;
alter table homework_obligation add constraint fk_r10 foreign key (homework_id)
references homework (homework_id) on delete restrict on update restrict;
alter table obligation_definition add constraint fk_r12 foreign key (proj_ob_id)
references project_obligation (proj_ob_id) on delete restrict on update restrict;
alter table obligation_definition add constraint fk_r13 foreign key (hw_ob_id)
references homework_obligation (hw_ob_id) on delete restrict on update restrict;
alter table obligation_definition add constraint fk_r14 foreign key (test_ob_id)
references test_obligation (test_ob_id) on delete restrict on update restrict;
alter table obligation_definition add constraint fk_r8 foreign key (sub_def_id)
references subject_definition (sub_def_id) on delete restrict on update restrict;
alter table professor add constraint fk_inheritance foreign key (person_id)
references person (person_id) on delete restrict on update restrict;
alter table project_obligation add constraint fk_r9 foreign key (project_id)
references project (project_id) on delete restrict on update restrict;
alter table student add constraint fk_inheritance2 foreign key (person_id)
references person (person_id) on delete restrict on update restrict;
alter table study_program add constraint fk_r2 foreign key (faculty_id)
references faculty (faculty_id) on delete restrict on update restrict;
alter table stud_sub add constraint fk_stud_sub foreign key (subject_id, stud_id)
references student (person_id, stud_id) on delete restrict on update restrict;
alter table stud_sub add constraint fk_stud_sub2 foreign key (subject_id)
references subject (subject_id) on delete restrict on update restrict;
alter table subject add constraint fk_r15 foreign key (subject_code, prof_id)
references professor (person_id, prof_id) on delete restrict on update restrict;
alter table subject_definition add constraint fk_r5 foreign key (curriculum_id)
references curriculum (curriculum_id) on delete restrict on update restrict;
alter table subject_definition add constraint fk_r7 foreign key (subject_id)
references subject (subject_id) on delete restrict on update restrict;
alter table test add constraint fk_r20 foreign key (question_id)
references question (question_id) on delete restrict on update restrict;
alter table test_obligation add constraint fk_r11 foreign key (test_id)
references test (test_id) on delete restrict on update restrict;
| true |
bbe8d8a252207a2b9d9ad810685d0dedd9d38c2d | SQL | Mtutak/Bamazon | /Bamazon.sql | UTF-8 | 1,308 | 3.65625 | 4 | [] | no_license | CREATE DATABASE Bamazon;
USE Bamazon;
CREATE TABLE products (
item_id INTEGER AUTO_INCREMENT NOT NULL,
product_name VARCHAR(50) NOT NULL,
department_name VARCHAR(50) NULL,
price DECIMAL(10,2) NOT NULL,
stock_quantity INTEGER NOT NULL,
primary key (item_id)
);
-- Added for part 3 --
USE Bamazon;
CREATE TABLE departments (
department_id INTEGER NOT NULL,
department_name VARCHAR(50) NOT NULL,
over_head_costs DECIMAL(10,2) NOT NULL,
total_sales DECIMAL(10,2) NOT NULL,
primary key (department_id)
);
USE Bamazon;
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("Rock Paper Coding", "Books", 50.00, 20),
("Flying Laptop", "Technology", 2000.00, 100),
("Emergent Athletic Shorts", "Apparel", 75.00, 10),
("PowerUp Coffee", "Food", 5.00, 200),
("Angry Birds", "Games", 1.00, 1000),
("Hoverboard", "Technology", 5000.00, 2),
("Space Jam Ball", "Sports", 20000.00, 1),
("Dragon Ball", "Wellness", 30000.00, 7),
("Steak", "Food", 10.00, 200),
("Batman Utility Belt", "Fashion", 2000.00, 3);
-- Modifying product table so that there is a product_sales column from Challenge 3 --
USE Bamazon;
ALTER TABLE products
ADD COLUMN product_sales DECIMAL(10,2) AFTER stock_quantity;
SELECT * FROM products; | true |
4e0502d4cf1b62e8e165fa8339b11b93e778f23c | SQL | JosephaGK/BlogCode | /study-shiro/src/main/resources/sql/roles_permissions_default.sql | UTF-8 | 1,174 | 3.0625 | 3 | [] | no_license | /*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 50717
Source Host : localhost:3306
Source Schema : study-shiro
Target Server Type : MySQL
Target Server Version : 50717
File Encoding : 65001
Date: 13/03/2019 21:18:56
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for roles_permissions
-- ----------------------------
DROP TABLE IF EXISTS `roles_permissions`;
CREATE TABLE `roles_permissions` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`role_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '角色名',
`permission` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '权限',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of roles_permissions
-- ----------------------------
INSERT INTO `roles_permissions` VALUES (1, 'admin', 'user:update');
SET FOREIGN_KEY_CHECKS = 1;
| true |
997e5817ca57b768b8922f3243b1152ae6c52848 | SQL | Reiuiji/ECE564-Database-Programming | /FinalExam/part1.sql | UTF-8 | 1,321 | 4.34375 | 4 | [
"MIT"
] | permissive | --1) Write an SQL statement which returns the fish scientific name, the average
-- number in stock and the average stock value (number in stock * price) for
-- the fish species (e.g. Chaetodon “butterfly fish” or Scaridae “parrot fish”)
-- for all the marine fish we have in stock. (10 pts)
PROMPT ================================
PROMPT | Running Part 1 |
PROMPT ================================
--Note: Run @table.sql @values.sql prior to see results
-- Assume only Stock for fish species for avg num in stock & stock value
SELECT scientific_name, AVG(number_in_stock) AS stock_num , AVG(number_in_stock*current_price) AS stock_value
FROM aquatic_organism_stock
WHERE number_in_stock > 0
AND NOT EXISTS ( -- Select any organism other than invertebrates
SELECT * FROM marine_invertebrates
WHERE marine_invertebrates.scientific_name = aquatic_organism_stock.scientific_name)
GROUP BY aquatic_organism_stock.scientific_name;
--total sum of available stock of all fish species
SELECT SUM(number_in_stock*current_price) AS Total_Stock_Value
FROM aquatic_organism_stock
WHERE number_in_stock > 0
AND NOT EXISTS ( -- Select any organism other than invertebrates
SELECT * FROM marine_invertebrates
WHERE marine_invertebrates.scientific_name = aquatic_organism_stock.scientific_name);
| true |
5a760223bbd2eabc978d7989f63071509d50e10a | SQL | manas0801/spring-security | /spring-security-with-user-datasource/src/main/resources/schema.sql | UTF-8 | 550 | 3.078125 | 3 | [] | no_license | create table if not exists users (id IDENTITY not null ,username varchar(45), password varchar(45),enabled INT ,primary key(id));
create table if not exists authorities (id IDENTITY not null ,username varchar(45),authority varchar(45), primary key(id));
INSERT INTO USERS (username,password,enabled) values('sumit','12345',1);
INSERT INTO USERS (username,password,enabled) values('amit','12345',1);
INSERT INTO authorities(username,authority) values ('sumit','read');
INSERT INTO authorities(username,authority) values ('amit','read'); | true |
075692336fd07db525ac625a62f266aff684297a | SQL | FUUK/fuuk | /fuuk/people/models/sql/updates/update-0.11-flatpage.mysql.sql | UTF-8 | 821 | 3.4375 | 3 | [] | no_license | INSERT INTO django_flatpage (id, url, title, title_en, title_cs, content, content_en, content_cs, enable_comments,
template_name, registration_required)
SELECT f.id, f.url, coalesce(f_en.title, ''), f_en.title, f_cs.title, coalesce(f_en.content, ''), f_en.content,
f_cs.content, f.enable_comments, f.template_name, f.registration_required
FROM multilingual_flatpage AS f
LEFT OUTER JOIN multilingual_flatpagetranslation AS f_en
ON (f.id=f_en.master_id AND f_en.language_code='en')
LEFT OUTER JOIN multilingual_flatpagetranslation AS f_cs
ON (f.id=f_cs.master_id AND f_cs.language_code='cs');
INSERT INTO django_flatpage_sites (flatpage_id, site_id)
SELECT flatpage_id, site_id FROM multilingual_flatpage_sites;
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.