More efficient way to write a TOP 1 * query? - sql

Below is an example of a query which I think is hindering my overall performance of my stored procedure (this operation is done several times in a loop). The temporary table #PROBLEMS_RELATED_REF_FINAL is a result of a few full outer joins and is without a primary key (because as you can see by my where clause, some of the would-be primary key columns, are null). I was wondering if there was a more efficient way to get the top record where all of the conditions are met (given that there is no primary key). #PROBLEMS_RELATED_REF_FINAL will generally have about 50-1000 records.
SELECT TOP 1 *, NULL AS [SUBTRACTION], NULL AS [END_COUNTER]
FROM #PROBLEMS_RELATED_REF_FINAL
WHERE [ST_1] IS NOT NULL
AND [ST_2] IS NOT NULL
AND [ST_3] IS NOT NULL
AND [ST_4] IS NOT NULL
The table create for #PROBLEMS_RELATED_REF_FINAL looks like this:
CREATE TABLE #PROBLEMS_RELATED_REF_FINAL (
[ST_1] CHAR(2) NULL,
[PUMA_1] CHAR(5) NULL,
[ZCTA_1] CHAR(5) NULL,
[X-XX_1] INT NULL,
[PUMA_PROBLEMS_1] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_1] INT NULL,
[COUNTER_1] INT NULL,
[ST_2] CHAR(2) NULL,
[PUMA_2] CHAR(5) NULL,
[ZCTA_2] CHAR(5) NULL,
[X-XX_2] INT NULL,
[PUMA_PROBLEMS_2] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_2] INT NULL,
[COUNTER_2] INT NULL,
[ST_3] CHAR(2) NULL,
[PUMA_3] CHAR(5) NULL,
[ZCTA_3] CHAR(5) NULL,
[X-XX_3] INT NULL,
[PUMA_PROBLEMS_3] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_3] INT NULL,
[COUNTER_3] INT NULL,
[ST_4] CHAR(2) NULL,
[PUMA_4] CHAR(5) NULL,
[ZCTA_4] CHAR(5) NULL,
[X-XX_4] INT NULL,
[PUMA_PROBLEMS_4] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_4] INT NULL,
[COUNTER_4] INT NULL,
[ST_5] CHAR(2) NULL,
[PUMA_5] CHAR(5) NULL,
[ZCTA_5] CHAR(5) NULL,
[X-XX_5] INT NULL,
[PUMA_PROBLEMS_5] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_5] INT NULL,
[COUNTER_5] INT NULL,
[ST_6] CHAR(2) NULL,
[PUMA_6] CHAR(5) NULL,
[ZCTA_6] CHAR(5) NULL,
[X-XX_6] INT NULL,
[PUMA_PROBLEMS_6] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_6] INT NULL,
[COUNTER_6] INT NULL,
[ST_7] CHAR(2) NULL,
[PUMA_7] CHAR(5) NULL,
[ZCTA_7] CHAR(5) NULL,
[X-XX_7] INT NULL,
[PUMA_PROBLEMS_7] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_7] INT NULL,
[COUNTER_7] INT NULL,
[ST_8] CHAR(2) NULL,
[PUMA_8] CHAR(5) NULL,
[ZCTA_8] CHAR(5) NULL,
[X-XX_8] INT NULL,
[PUMA_PROBLEMS_8] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_8] INT NULL,
[COUNTER_8] INT NULL,
[ST_9] CHAR(2) NULL,
[PUMA_9] CHAR(5) NULL,
[ZCTA_9] CHAR(5) NULL,
[X-XX_9] INT NULL,
[PUMA_PROBLEMS_9] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_9] INT NULL,
[COUNTER_9] INT NULL,
[ST_10] CHAR(2) NULL,
[PUMA_10] CHAR(5) NULL,
[ZCTA_10] CHAR(5) NULL,
[X-XX_10] INT NULL,
[PUMA_PROBLEMS_10] CHAR(1) NULL,
[NEEDED_PUMA_GROWTH_10] INT NULL,
[COUNTER_10] INT NULL)
ON [PRIMARY]
Any insight would be greatly appreciated.

Related

Can a value be a primary and a foreign key?

I have the following tables in my SQL Server database.
Customer is a subtype of User thus I made a reference from Customer to User.
I also want to link my customer to my reservation. I'd like to use the Foreign key in the Customer table as a PK for this relation. When I write this out in SQL Server, I get this error under "(userid)":
Invalid column 'userid'
How can I make this relation?
Create table [dbo].[User]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[name] varchar(50) NOT NULL,
[password] nvarchar(100) NOT NULL,
)
Create table [dbo].[Customer]
(
[userid] int FOREIGN KEY REFERENCES [dbo].[User](id) NOT NULL,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
)
Create table [dbo].[Reservation]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[datum] date NOT NULL,
[prijs] decimal NOT NULL,
[levertijd] datetime NOT NULL,
[ophaaltijd] datetime NOT NULL,
[leverAdres] varchar(60) NOT NULL,
[klantId] int FOREIGN KEY REFERENCES [dbo].[Customer](userid) NOT NULL
)
yes this is possible, try it like this
Create table [dbo].[Customer]
(
[userid] int not null,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
constraint PK_UserID primary key ([userid]),
constraint FK_Customer_User foreign key (userid) references [User] (id)
)
But I have to say that userid seems like an odd primary key for a table called Customer
I would so something like this :
Create table [dbo].[Customer]
(
[CustomerID] int not null identity,
[userid] int not null,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
constraint PK_CustomerID primary key ([CustomerID]),
constraint FK_Customer_User foreign key (userid) references [User] (id)
)
Create table [dbo].[Reservation]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[datum] date NOT NULL,
[prijs] decimal NOT NULL,
[levertijd] datetime NOT NULL,
[ophaaltijd] datetime NOT NULL,
[leverAdres] varchar(60) NOT NULL,
[klantId] int FOREIGN KEY REFERENCES [dbo].[Customer](customerid) NOT NULL
)

Importing .sql file into SQL Server 2012

I have database with .sql, I want to import that .sql file into SQL Server 2012 using Management Studio.
When I tried to import the data, I'm getting an error:
Msg 156, Level 15, State 1, Line 76
Incorrect syntax near the keyword 'NOT'.
[![enter image description here][1]][1]
CREATE TABLE ct_bookings(
id int NOT NULL,
order_id bigint NOT NULL,
client_id bigint NOT NULL,
order_date date NOT NULL,
booking_date_time datetime NOT NULL,
service_id int NOT NULL,
method_id int NOT NULL,
method_unit_id int NOT NULL,
method_unit_qty int NOT NULL,
method_unit_qty_rate double NOT NULL,
booking_status varchar(10) not null ('A','C','R','CC','CS','CO','MN','RS') NOT NULL COMMENT 'A=active, C=confirm, R=Reject, CC=Cancel by Client, CS=Cancel by service provider,CO=Completed,MN=MARK AS NOSHOW',
`reject_reason` varchar(200) NOT NULL,
`reminder_status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '0=Email Not Sent,1=Email Sent',
`lastmodify` datetime NOT NULL,
`read_status` enum('R','U') NOT NULL DEFAULT 'U'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
How can I solve this issue?
Please help me out. Thanks in advance.
in MySQL:-
CREATE TABLE ct_addon_service_rate(
id int(11) NOT NULL,
addon_service_id int(11) NOT NULL,
unit varchar(20) NOT NULL,
rules VARCHAR(10) NOT NULL CHECK (rules IN('E', 'G')),
rate DOUBLE NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Equals in SQL Server:-
Create TABLE ct_addon_service_rate (
id int NOT NULL,
addon_service_id int NOT NULL,
unit varchar(20) NOT NULL,
rules char(1) not null,
rate FLOAT(25) NOT NULL,
CHECK (rules in ('E', 'G'))
)
Update:-
In MySQL:-
CREATE TABLE ct_bookings(
id int NOT NULL,
order_id bigint NOT NULL,
client_id bigint NOT NULL,
order_date date NOT NULL,
booking_date_time datetime NOT NULL,
service_id int NOT NULL,
method_id int NOT NULL,
method_unit_id int NOT NULL,
method_unit_qty int NOT NULL,
method_unit_qty_rate double NOT NULL,
booking_status varchar(10) not null ('A','C','R','CC','CS','CO','MN','RS') NOT NULL COMMENT 'A=active, C=confirm, R=Reject, CC=Cancel by Client, CS=Cancel by service provider,CO=Completed,MN=MARK AS NOSHOW',
`reject_reason` varchar(200) NOT NULL,
`reminder_status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '0=Email Not Sent,1=Email Sent',
`lastmodify` datetime NOT NULL,
`read_status` enum('R','U') NOT NULL DEFAULT 'U'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Equals in SQL Server:-
CREATE TABLE ct_bookings(
id int NOT NULL,
order_id bigint NOT NULL,
client_id bigint NOT NULL,
order_date date NOT NULL,
booking_date_time datetime NOT NULL,
service_id int NOT NULL,
method_id int NOT NULL,
method_unit_id int NOT NULL,
method_unit_qty int NOT NULL,
method_unit_qty_rate float(25) NOT NULL,
booking_status varchar(10) not null check (booking_status in ('A','C','R','CC','CS','CO','MN','RS')),
/*COMMENT 'A=active, C=confirm, R=Reject, CC=Cancel by Client, CS=Cancel by service provider,CO=Completed,MN=MARK AS NOSHOW', */
reject_reason varchar(200) NOT NULL,
reminder_status char(1)NOT NULL check (reminder_status in ('0','1')) DEFAULT '0', /*COMMENT '0=Email Not Sent,1=Email Sent', */
lastmodify datetime NOT NULL,
read_status char(1) NOT NULL check (read_status in ('R','U')) DEFAULT 'U'
)
Update 2:-
in MySQL:-
CREATE TABLE ct_email_templates (
id int NOT NULL,
email_subject varchar(200) COLLATE Latin1_General_CI_AS NOT NULL,
email_message text COLLATE Latin1_General_CI_AS NOT NULL,
default_message text COLLATE Latin1_General_CI_AS NOT NULL,
email_template_status varchar(10) NOT NULL check(email_template_status in('E','D')) COLLATE Latin1_General_CI_AS,
email_template_type varchar(10) check(email_template_type IN('A','C','R','CC','RS','RM')) COLLATE Latin1_General_CI_AS NOT NULL COMMENT 'A=active, C=confirm, R=Reject, CC=Cancel by Client, RS=Reschedule, RM=Reminder',
user_type` enum('A','C') COLLATE utf8_unicode_ci NOT NULL COMMENT 'A=Admin,C=client'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Equals in SQL Server:-
CREATE TABLE ct_email_templates (
id int NOT NULL,
email_subject varchar(200) COLLATE Latin1_General_CI_AS NOT NULL,
email_message text COLLATE Latin1_General_CI_AS NOT NULL,
default_message text COLLATE Latin1_General_CI_AS NOT NULL,
email_template_status varchar(10) COLLATE Latin1_General_CI_AS NOT NULL check(email_template_status in('E','D')) ,
email_template_type varchar(10) COLLATE Latin1_General_CI_AS check(email_template_type IN('A','C','R','CC','RS','RM')) NOT NULL, /*COMMENT 'A=active, C=confirm, R=Reject, CC=Cancel by Client, RS=Reschedule, RM=Reminder',
user_type` enum('A','C') COLLATE utf8_unicode_ci NOT NULL COMMENT 'A=Admin,C=client' */
)

IBM SQL Database import not working

I am trying to import my sql schema in IBM SQL Database (sqldb_free plan)
CREATE TABLE User (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(45) NOT NULL,
password VARCHAR(120) NULL,
salt VARCHAR(45) NULL,
authData VARCHAR(45) NULL,
CreditCardId VARCHAR(120) NULL,
DisplayUsername VARCHAR(120) NOT NULL,
email VARCHAR(120) NOT NULL,
cashBalance FLOAT NULL DEFAULT 0,
city VARCHAR(45) NULL,
country VARCHAR(45) NULL,
dob TIMESTAMP(4) NULL,
firstName VARCHAR(45) NOT NULL,
lastName VARCHAR(45) NULL,
gender TINYINT(1) NULL DEFAULT 1,
playerPoints INT NULL DEFAULT 0,
state CHAR(2) NULL,
tickets INT NULL,
userImage VARCHAR(240) NULL,
createdAt TIMESTAMP(4) NOT NULL DEFAULT CURRENT_TIMESTAMP,
revision VARCHAR(20) NULL,
cakeReqId VARCHAR(15) NULL,
cakeAffId VARCHAR(15) NULL,
signUpEvent TINYINT(1) NOT NULL DEFAULT 0,
depositEvent TINYINT(1) NOT NULL DEFAULT 0,
SignupSource VARCHAR(20) NULL,
TotalSpent FLOAT NULL DEFAULT 0,
address VARCHAR(120) NULL,
phone VARCHAR(45) NULL,
TicketTransferrable INT NULL,
updatedAt TIMESTAMP(4) NOT NULL DEFAULT CURRENT_TIMESTAMP,
FavouriteTeam INT NULL,
UNIQUE INDEX email_UNIQUE (email ASC),
PRIMARY KEY (id));
And the error message is
DDL failed with message
_ Exception. _ state = 42601; error code = -104; error Message = Error for batch element #1: An unexpected token "," was found following "NULL AUTO_INCREMENT". Expected tokens may include: "".. _CODE=-104, _STATE=42601, DRIVER=3.66.46
How can i fix this?
The DDL statement have the following issues:
DB2 does not support the "AUTO_INCREMENT" replace with "GENERATED ALWAYS AS IDENTITY".
DB2 does not support the TINYINT datatype replace with INT or CHARACTER(1) depends of your data.
CREATE UNIQUE INDEX separately, delete "UNIQUE INDEX email_UNIQUE (email ASC)," and add a DDL index.
Following as you could fix it:
CREATE TABLE User (
id INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1),
username VARCHAR(45) NOT NULL,
password VARCHAR(120) NULL,
salt VARCHAR(45) NULL,
authData VARCHAR(45) NULL,
CreditCardId VARCHAR(120) NULL,
DisplayUsername VARCHAR(120) NOT NULL,
email VARCHAR(120) NOT NULL,
cashBalance FLOAT NULL DEFAULT 0,
city VARCHAR(45) NULL,
country VARCHAR(45) NULL,
dob TIMESTAMP(4) NULL,
firstName VARCHAR(45) NOT NULL,
lastName VARCHAR(45) NULL,
gender TINYINT(1) NULL DEFAULT 1,
playerPoints INT NULL DEFAULT 0,
state CHAR(2) NULL,
tickets INT NULL,
userImage VARCHAR(240) NULL,
createdAt TIMESTAMP(4) NOT NULL DEFAULT CURRENT_TIMESTAMP,
revision VARCHAR(20) NULL,
cakeReqId VARCHAR(15) NULL,
cakeAffId VARCHAR(15) NULL,
signUpEvent TINYINT(1) NOT NULL DEFAULT 0,
depositEvent TINYINT(1) NOT NULL DEFAULT 0,
SignupSource VARCHAR(20) NULL,
TotalSpent FLOAT NULL DEFAULT 0,
address VARCHAR(120) NULL,
phone VARCHAR(45) NULL,
TicketTransferrable INT NULL,
updatedAt TIMESTAMP(4) NOT NULL DEFAULT CURRENT_TIMESTAMP,
FavouriteTeam INT NULL,
PRIMARY KEY (id));
CREATE UNIQUE INDEX email_UNIQUE
ON user
(
email ASC
)
;

ORA-00907: missing right parenthesis (With Examples)

I'm trying to create this table in SQL.
CREATE TABLE Orders (
order_id int(10) NOT NULL,
order_date date NOT NULL,
total_value varchar(250) DEFAULT NULL,
order_status varchar(250) DEFAULT NULL,
payment_type_id int(10) NOT NULL,
delivery_id int(10) DEFAULT NULL,
store_id int(10) NOT NULL,
staff_id int(10) DEFAULT NULL,
client_id int(10) NOT NULL,
sale_type_id int(10) NOT NULL
);
I gives me [Err] ORA-00907: missing right parenthesis
I really don't know why. I already searched a lot, I put this example:
CREATE TABLE suppliers (
supplier_id number(10) NOT NULL,
supplier_name varchar2(50) NOT NULL,
contact_name varchar2(50)
);
And it works! But it's the same as mine, so why does it give this error?
You dont have to define the length of int. Remove the (10)
CREATE TABLE Orders (
order_id int NOT NULL,
order_date date NOT NULL,
total_value varchar(250) DEFAULT NULL,
order_status varchar(250) DEFAULT NULL,
payment_type_id int NOT NULL,
delivery_id int DEFAULT NULL,
store_id int NOT NULL,
staff_id int DEFAULT NULL,
client_id int NOT NULL,
sale_type_id int NOT NULL
);
SQL FIDDLE DEMO
Remove the (10) from all the ints, or change it all to number(10), like so
CREATE TABLE Orders (
order_id int NOT NULL,
order_date date NOT NULL,
total_value varchar(250) DEFAULT NULL,
order_status varchar(250) DEFAULT NULL,
payment_type_id int NOT NULL,
delivery_id int DEFAULT NULL,
store_id int NOT NULL,
staff_id int DEFAULT NULL,
client_id int NOT NULL,
sale_type_id int NOT NULL
);

SQL table creation code gives error

could someone have a look at this for me, I can't seem to find why it is not working.
CREATE TABLE Person(
Person_ID int auto_increment NOT NULL,
Person_Type_ID int NOT NULL,
Create_Date datetime NOT NULL ,
Modify_Date datetime NOT NULL ,
First_Name varchar(50) NOT NULL,
Surname varchar(50) NOT NULL,
DOB date NOT NULL,
Gender char(1) NOT NULL CHECK (Gender ='f' OR Gender ='m'),
Archive char(1) NULL,
Allergies varchar(200) NOT NULL,
Dietry_Requirements varchar(200) NOT NULL,
Disabilities varchar(200) NOT NULL,
Medicine_Requirements varchar(200) NOT NULL,
username varchar (30) NOT NULL,
password varchar (30) NOT NULL,
CONSTRAINT PK_Person_ID PRIMARY KEY (Person_ID)
CONSTRAINT FK_Person_Type_ID FOREIGN KEY (Person_Type_ID)
REFERENCES Person_Type (Person_Type_ID));
You missed a comma! This should work...
CREATE TABLE Person(
Person_ID int auto_increment NOT NULL,
Person_Type_ID int NOT NULL,
Create_Date datetime NOT NULL ,
Modify_Date datetime NOT NULL ,
First_Name varchar(50) NOT NULL,
Surname varchar(50) NOT NULL,
DOB date NOT NULL,
Gender char(1) NOT NULL CHECK (Gender ='f' OR Gender ='m'),
Archive char(1) NULL,
Allergies varchar(200) NOT NULL,
Dietry_Requirements varchar(200) NOT NULL,
Disabilities varchar(200) NOT NULL,
Medicine_Requirements varchar(200) NOT NULL,
username varchar (30) NOT NULL,
password varchar (30) NOT NULL,
CONSTRAINT PK_Person_ID PRIMARY KEY (Person_ID),
CONSTRAINT FK_Person_Type_ID FOREIGN KEY (Person_Type_ID)
REFERENCES Person_Type (Person_Type_ID));