Incorrect syntax near 'a' with enum('a','b','c') - sql

CREATE TABLE ec_recurring
(
[recurring id] int NOT NULL IDENTITY,
[price] decimal(10,4) NOT NULL,
[frequency] enum('day','week','semi_month','month','year') NOT NULL,
[duration] cast(10 as int) unsigned NOT NULL,
[cycle] cast(10 as int) unsigned NOT NULL,
[trial status] tinyint(4) NOT NULL,
[trial price] decimal(10,4) NOT NULL,
[trial frequency] enum('day','week','semi_month','month','year') NOT NULL,
[trial duration] cast(10 as int) unsigned NOT NULL,
[trial cycle] cast(10 as int) unsigned NOT NULL,
[status] tinyint(4) NOT NULL,
[sort order] cast(11 as int) NOT NULL,
[date created] datetime2 NOT NULL,
[date modified] datetime2 NOT NULL,
[created by] varchar(20) NOT NULL,
[modified by] varchar(20) NOT NULL,
[active] tinyint(4) NOT NULL,
PRIMARY KEY ([recurring id])
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
This was my code. Why does this error happen near day and cast?
Msg 102, Level 15, State 1, Line 3922
Incorrect syntax near 'day'

If we are talking about T-SQL, then the error near day means that the syntax is incorrect (simply there is no enum keyword in T-SQL), it should be something like this:
[frequency] VARCHAR(10) NOT NULL,
CONSTRAINT ck_Enum CHECK ([frequency] IN('day','week','semi_month','month','year')),
Considering the second error you use cast in the wrong context, SQL doesn't know the type of the column. I believe that you wanted to write:
[duration] INT DEFAULT 10 NOT NULL
CONSTRAINT ck_Duration CHECK ([duration] > 0),
With additional checking whether duration is unsigned. You should obey the language's syntax because you have some more errors. Let the following be an example for you:
CREATE TABLE ec_recurring
(
[recurring id] INT IDENTITY NOT NULL
CONSTRAINT pl_recId PRIMARY KEY,
[price] DECIMAL(10, 4) NOT NULL,
[frequency] VARCHAR(10) NOT NULL,
CONSTRAINT ck_Enum CHECK ([frequency] IN('day','week','semi_month','month','year')),
[duration] INT DEFAULT 10 NOT NULL
CONSTRAINT ck_Duration CHECK ([duration] > 0),
[cycle] INT DEFAULT 10 NOT NULL
CONSTRAINT ck_Cycle CHECK ([cycle] > 0),
[trial status] TINYINT DEFAULT 4 NOT NULL,
[trial price] DECIMAL(10, 4) NOT NULL,
[trial frequency] VARCHAR(10) NOT NULL
CONSTRAINT ck_TrialEnum CHECK ([trial frequency] IN('day','week','semi_month','month','year')),
[trial duration] INT DEFAULT 10 NOT NULL
CONSTRAINT ck_TrialDuration CHECK ([trial duration] > 0),
[trial cycle] INT DEFAULT 10 NOT NULL
CONSTRAINT ck_TrialCycle CHECK ([trial cycle] > 0),
[status] TINYINT DEFAULT 4 NOT NULL,
[sort order] INT DEFAULT 11 NOT NULL,
[date created] DATETIME2 NOT NULL,
[date modified] DATETIME2 NOT NULL,
[created by] DATETIME NOT NULL,
[modified by] DATETIME NOT NULL,
[active] TINYINT DEFAULT 4 NOT NULL,
);

In Microsoft's SQL Server is no such thing as enum, it is from MySql, but you can use its equivalent:
mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))
Original Post

Related

How to optimize sql multiple select queries?

I have a query that calculates wait time for each record from the Transactions table and calculates SUM and MAX wait time for each of the group below based on receivedDate and claimedDt.
Here is a basic query:
SELECT
'2022-06-01' as reportDate,
waitTimeSubQuery.currentAssignedQueueId,
waitTimeSubQuery.queueAccessPointId,
waitTimeSubQuery.queueName AS QueueName,
waitTimeSubQuery.queueReportCategory,
waitTimeSubQuery.queuePriority,
waitTimeSubQuery.queueOrganizationHierarchyId,
COUNT(waitTimeSubQuery.id) AS totalCasesWaiting,
SUM(CASE WHEN waitTimeSubQuery.waitTimeMinutes > 0 THEN waitTimeSubQuery.waitTimeMinutes ELSE 0 END) AS sumWaitTimeMinutes,
MAX(CASE WHEN waitTimeSubQuery.waitTimeMinutes > 0 THEN waitTimeSubQuery.waitTimeMinutes ELSE 0 END) AS maxWaitTimeMinutes
FROM (SELECT
id,
currentAssignedQueueId,
queueAccessPointId,
queueName,
queueReportCategory,
queuePriority,
queueOrganizationHierarchyId,
(CASE WHEN (receivedDateUTC > '0001-01-01T00:00:00Z' OR receivedDate > '0001-01-01T00:00:00Z') AND (appointmentDT IS NULL OR appointmentDT < '2022-09-28T12:58:47')
THEN CAST(DateDiff(MINUTE,
CASE WHEN receivedDateUTC > '0001-01-01T00:00:00Z'
THEN CONCAT(SUBSTRING(CAST(receivedDateUTC AS VARCHAR), 0, 19), 'Z')
ELSE TRY_CAST(CONCAT(CONCAT(SUBSTRING(CAST(receivedDate AS VARCHAR), 0, 10), SUBSTRING(CAST(createdDT AS VARCHAR), 10, 9)), 'Z') AS DATETIME2) END,
CASE WHEN claimedDT > '0001-01-01T00:00:00Z' AND claimedDT < '2022-06-01T23:59:00Z' AND transactionStatus != 'WaitingAssignment'
THEN CONCAT(SUBSTRING(CAST(claimedDT AS VARCHAR), 0, 19), 'Z')
ELSE '2022-06-01T23:59:00Z' END
) AS BIGINT)
ELSE 0 END) AS waitTimeMinutes
FROM #transactionsList
WHERE receivedDate <= '2022-06-01T00:00:00'
AND (claimedDT >= '2022-06-02T00:00:00' OR transactionStatus = 'WaitingAssignment')) waitTimeSubQuery
GROUP BY waitTimeSubQuery.currentAssignedQueueId,
waitTimeSubQuery.queueAccessPointId,
waitTimeSubQuery.queueName,
waitTimeSubQuery.queueReportCategory,
waitTimeSubQuery.queuePriority,
waitTimeSubQuery.queueOrganizationHierarchyId
I want to calculate statistics for each day for the period of 30 days and the only difference is dates used for calculating waitTimeMinutes (based on endDate, claimedDt, receivedDate) and filtering by receivedDate and claimedDt.
I tried to save sub-set of the Transactions data into a table variable and reuse it in multiple select queries to get the statistics for each day, but this script runs too slow
Here is the code:
DECLARE #transactionsList TABLE (
id UNIQUEIDENTIFIER,
currentAssignedQueueId UNIQUEIDENTIFIER,
queueAccessPointId UNIQUEIDENTIFIER,
queueName VARCHAR(100),
queueReportCategory VARCHAR(100),
queuePriority INT,
queueOrganizationHierarchyId UNIQUEIDENTIFIER,
receivedDate DATE,
claimedDT DATE,
transactionStatus VARCHAR(100),
receivedDateUTC DATE,
appointmentDT DATE,
createdDT DATE)
INSERT INTO #transactionsList
SELECT
Transactions.id,
Transactions.currentAssignedQueueId,
Queues.accessPointId as queueAccessPointId,
Queues.name as queueName,
Queues.reportCategory as queueReportCategory,
Queues.priority as queuePriority,
Queues.organizationHierarchyId as queueOrganizationHierarchyId,
Transactions.receivedDate,
Transactions.claimedDT,
Transactions.transactionStatus,
Transactions.receivedDateUTC,
Transactions.appointmentDT,
Transactions.createdDT
FROM Transactions
LEFT JOIN Queues ON Transactions.currentAssignedQueueId = Queues.Id
WHERE Transactions.consumerId = '66458f4a-b3d4-4f80-93d4-5aa3ea123249'
AND Transactions.isActive = 1
AND Transactions.receivedDate <= '2022-06-30T00:00:00'
AND (Transactions.claimedDT >= '2022-06-02T00:00:00' OR Transactions.transactionStatus = 'WaitingAssignment')
--SELECT COUNT(*) FROM #transactionsList
-- 2022-06-01
SELECT
'2022-06-01' as reportDate,
waitTimeSubQuery.currentAssignedQueueId,
waitTimeSubQuery.queueAccessPointId,
waitTimeSubQuery.queueName AS QueueName,
waitTimeSubQuery.queueReportCategory,
waitTimeSubQuery.queuePriority,
waitTimeSubQuery.queueOrganizationHierarchyId,
COUNT(waitTimeSubQuery.id) AS totalCasesWaiting,
SUM(CASE WHEN waitTimeSubQuery.waitTimeMinutes > 0 THEN waitTimeSubQuery.waitTimeMinutes ELSE 0 END) AS sumWaitTimeMinutes,
MAX(CASE WHEN waitTimeSubQuery.waitTimeMinutes > 0 THEN waitTimeSubQuery.waitTimeMinutes ELSE 0 END) AS maxWaitTimeMinutes
FROM (SELECT
id,
currentAssignedQueueId,
queueAccessPointId,
queueName,
queueReportCategory,
queuePriority,
queueOrganizationHierarchyId,
(CASE WHEN (receivedDateUTC > '0001-01-01T00:00:00Z' OR receivedDate > '0001-01-01T00:00:00Z') AND (appointmentDT IS NULL OR appointmentDT < '2022-09-28T12:58:47')
THEN CAST(DateDiff(MINUTE,
CASE WHEN receivedDateUTC > '0001-01-01T00:00:00Z'
THEN CONCAT(SUBSTRING(CAST(receivedDateUTC AS VARCHAR), 0, 19), 'Z')
ELSE TRY_CAST(CONCAT(CONCAT(SUBSTRING(CAST(receivedDate AS VARCHAR), 0, 10), SUBSTRING(CAST(createdDT AS VARCHAR), 10, 9)), 'Z') AS DATETIME2) END,
CASE WHEN claimedDT > '0001-01-01T00:00:00Z' AND claimedDT < '2022-06-01T23:59:00Z' AND transactionStatus != 'WaitingAssignment'
THEN CONCAT(SUBSTRING(CAST(claimedDT AS VARCHAR), 0, 19), 'Z')
ELSE '2022-06-01T23:59:00Z' END
) AS BIGINT)
ELSE 0 END) AS waitTimeMinutes
FROM #transactionsList
WHERE receivedDate <= '2022-06-01T00:00:00'
AND (claimedDT >= '2022-06-02T00:00:00' OR transactionStatus = 'WaitingAssignment')) waitTimeSubQuery
GROUP BY waitTimeSubQuery.currentAssignedQueueId,
waitTimeSubQuery.queueAccessPointId,
waitTimeSubQuery.queueName,
waitTimeSubQuery.queueReportCategory,
waitTimeSubQuery.queuePriority,
waitTimeSubQuery.queueOrganizationHierarchyId
And the part from '2022-06-01' repeats 30 times for each day from the range respectively.
Is there any possibility to optimize this script? For my data it runs nearly 49 seconds and the number of the records in the table is only 7kk and it's far way more on other environment.
---EDIT---
Here are the definitions for the tables Transactions and Queues
CREATE TABLE [dbo].[Transactions] (
[id] UNIQUEIDENTIFIER NULL,
[accessPointId] UNIQUEIDENTIFIER NULL,
[isNonLobby] BIT NULL,
[printReceipt] BIT NULL,
[isExpressed] BIT NULL,
[isAssignedBySupervisor] BIT NULL,
[dateAssignedBySupervisor] VARCHAR (30) NULL,
[dateAssignedBySupervisorLocal] DATETIMEOFFSET (7) NULL,
[supervisorOverrideId] UNIQUEIDENTIFIER NULL,
[supervisorId] UNIQUEIDENTIFIER NULL,
[isNewHousehold] BIT NULL,
[householdId] UNIQUEIDENTIFIER NULL,
[receivedDate] DATE NULL,
[receivedDateUTC] DATETIME2 (7) NULL,
[transactionStatus] VARCHAR (20) NULL,
[claimedDT] DATETIME2 (7) NULL,
[claimedDTLocal] DATE NULL,
[initiallyClaimedById] UNIQUEIDENTIFIER NULL,
[completedDT] DATETIME2 (7) NULL,
[appointmentDT] DATETIME2 (7) NULL,
[completedDTLocal] DATE NULL,
[completedById] UNIQUEIDENTIFIER NULL,
[remarks] VARCHAR (MAX) NULL,
[currentAssignedQueueId] UNIQUEIDENTIFIER NULL,
[currentAssignedUserId] UNIQUEIDENTIFIER NULL,
[preTriageTransactionId] UNIQUEIDENTIFIER NULL,
[isAddClaim] BIT NULL,
[receiptId] UNIQUEIDENTIFIER NULL,
[ticketNumber] VARCHAR (100) NULL,
[deliNumber] VARCHAR (100) NULL,
[tasksCount] BIGINT NULL,
[projectedWaitTime] BIGINT NULL,
[actualWaitTimeMinutes] BIGINT NULL,
[assignWaitTime] BIGINT NULL,
[transactionTimeMinutes] BIGINT NULL,
[triageTimeMinutes] BIGINT NULL,
[outcomeId] UNIQUEIDENTIFIER NULL,
[outcomeReasonId] UNIQUEIDENTIFIER NULL,
[outcomeType] VARCHAR (50) NULL,
[dueDate] VARCHAR (30) NULL,
[dueDateLocal] DATETIMEOFFSET (7) NULL,
[isDueDateToday] VARCHAR (30) NULL,
[isUnknownHousehold] BIT NULL,
[activityId] UNIQUEIDENTIFIER NULL,
[programId] UNIQUEIDENTIFIER NULL,
[reviewMonthDueDate] VARCHAR (40) NULL,
[reviewMonthDueDateLocal] DATETIMEOFFSET (7) NULL,
[officeId] UNIQUEIDENTIFIER NULL,
[isOnceManuallyPaused] BIT NULL,
[pkey] VARCHAR (100) NULL,
[isActive] BIT NULL,
[consumerId] UNIQUEIDENTIFIER NULL,
[organizationName] VARCHAR (50) NULL,
[modifiedBy] UNIQUEIDENTIFIER NULL,
[modifiedDT] DATETIME2 (7) NULL,
[modifiedDTLocal] DATE NULL,
[createdBy] UNIQUEIDENTIFIER NULL,
[createdDT] DATETIME2 (7) NULL,
[createdDTLocal] DATE NULL,
[_ts] BIGINT NULL,
[type] VARCHAR (50) NULL,
[timezoneId] VARCHAR (50) NULL
);
CREATE TABLE [dbo].[Queues] (
[id] UNIQUEIDENTIFIER NULL,
[name] VARCHAR (255) NULL,
[accessPointId] UNIQUEIDENTIFIER NULL,
[organizationHierarchyId] UNIQUEIDENTIFIER NULL,
[assignedOrganizationHierarchyLevel] VARCHAR (20) NULL,
[bundlingGroup] BIGINT NULL,
[reportCategory] VARCHAR (100) NULL,
[priority] INT NULL,
[businessProcessThreshold] BIGINT NULL,
[calculateProjectedWaitTime] BIT NULL,
[waitTimeUnits] VARCHAR (10) NULL,
[hasCarryOver] BIT NULL,
[defaultTransactionTimeMinutes] BIGINT NULL,
[latestQueueMetricId] UNIQUEIDENTIFIER NULL,
[isAppointment] BIT NULL,
[consumerId] UNIQUEIDENTIFIER NULL,
[organizationName] VARCHAR (50) NULL,
[modifiedBy] UNIQUEIDENTIFIER NULL,
[modifiedDT] DATE NULL,
[createdBy] UNIQUEIDENTIFIER NULL,
[createdDT] DATE NULL,
[_ts] BIGINT NULL
);
And an index for the Transactions table (this is the only one index for this table and there are no indexes for the Queues table):
CREATE NONCLUSTERED INDEX [nci_wi_Transactions_EBAFDE3A7C2969265E76135FBA69188D] ON [dbo].[Transactions]
(
[consumerId] ASC,
[isActive] ASC,
[receivedDate] ASC
)
INCLUDE([appointmentDT],[claimedDT],[createdDT],[currentAssignedQueueId],[id],[receivedDateUTC],[transactionStatus]) WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
Here is the link on GitHub for the execution plan and the full query
https://github.com/sskotliar/query_optimization
PasteThePlan link
Option - 1
You can improve the performance of your query by using a CTE. How does CTE work? The query you write inside the WITH command is executed only once, and its result is stored as a temporary table. This allows you to execute your large query with multiple join in it once. In the remaining cases, only its result is used. But as I understood you call your query with different filters. If this is true, so please see Option 2.
Option - 2
If the result of your repeatable query is large, and you call this query with different filters, it is recommended that you, insert result of repeatable query into temp table, then create needed indexes for this temp table. Then you can use that table as much as you need. Since your table has indexes so your filters will be works high performance.
For each of the options mentioned above, it is recommended that you view Query Plan. Because the query plan may change from the DB side depending on the count of records in the tables.

I am trying to create a table in SQL and keep getting an error

I'm using Teradata SQL assistant to create a table. The code I am using is as follows:
CREATE TABLE calendar
(
CalendarKey INT NOT NULL,
FullDate DATE NOT NULL,
DayOfWeek VARCHAR(20) NOT NULL,
DayOfMonth INT NOT NULL,
Month VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
Year VARCHAR(4) NOT NULL
PRIMARY KEY (CalendarKey)
);
I get this error when I try to execute the command:
[Teradata Database] [3707] Syntax error, expected something like a 'CHECK' keyword between ',' and the 'Month' keyword.
Does anyone know what the issue is?
As the error implies month (and year, too) is a reserved keyword in Teradata, which can't be used as column name.
You might double quote it (but then you have to double quote it in every query, too) or you change the name. There's another issue, a missing comma before the primary key constraint:
CREATE TABLE calendar
(
CalendarKey INT NOT NULL,
FullDate DATE NOT NULL,
DayOfWeek VARCHAR(20) NOT NULL,
DayOfMonth INT NOT NULL,
"Month" VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
"Year" VARCHAR(4) NOT NULL,
PRIMARY KEY (CalendarKey)
);
Try this way
CREATE TABLE calendar (
CalendarKey INT NOT NULL,
FullDate DATE NOT NULL,
DayOfWeek VARCHAR(20) NOT NULL,
DayOfMonth INT NOT NULL,
Month VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
Year VARCHAR(4) NOT NULL
)
and
ALTER TABLE `calendar` ADD PRIMARY KEY (`CalendarKey`);
Try this, to have a table with PK as part of Table Definition
CREATE TABLE calendar
(
CalendarKey INT PRIMARY KEY NOT NULL,
FullDate DATE NOT NULL,
[DayOfWeek] VARCHAR(20) NOT NULL,
[DayOfMonth] INT NOT NULL,
[Month] VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
[Year] VARCHAR(4) NOT NULL
);
Or this to have Primary Key PK with an Identity [auto counter]
CREATE TABLE calendar
(
CalendarKey INT PRIMARY KEY Identity(1,1) NOT NULL,
FullDate DATE NOT NULL,
[DayOfWeek] VARCHAR(20) NOT NULL,
[DayOfMonth] INT NOT NULL,
[Month] VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
[Year] VARCHAR(4) NOT NULL
);
- Note, it's recommended to use prackets [] if the col name is a reserved key-word , like [year]

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' */
)

I need to create a view in the database

I need to create a view in the database when two columns are refer from same table. I can create a view like this:
CREATE VIEW [dbo].[ViewJournal]
AS
SELECT
J. d, J.date, J.drac, L.name as draccount, J.crac,
L.name as craccount, J.dramt, J.cramt, J.lf,
J.description, J.voucherType, J.reg_date, J.last_update,
J.active
FROM
Journal J, Ledger L
WHERE
J.drac = L.Id
But the result doesn't not show actual result.
Here, crac and drac are refered to from Ledger table.
Journal table:
CREATE TABLE [dbo].[Journal]
(
[Id] DECIMAL (18) IDENTITY (1, 1) NOT NULL,
[date] DATETIME NULL,
[drac] DECIMAL (18) NULL,
[crac] DECIMAL (18) NULL,
[dramt] DECIMAL (18, 2) NULL,
[cramt] DECIMAL (18, 2) NULL,
[reg_date] DATETIME NULL,
[last_update] DATETIME NULL,
[active] INT NULL,
[lf] VARCHAR (50) NULL,
[description] NVARCHAR (150) NULL,
[voucherType] VARCHAR (50) NULL,
[sales] VARCHAR (50) NULL,
[purchase] VARCHAR (50) NULL,
[cash_paymentno] VARCHAR (50) NULL,
[cash_receiptno] VARCHAR (50) NULL,
[expense] VARCHAR (50) NULL,
[income] VARCHAR (50) NULL,
[advance] VARCHAR (50) NULL,
[remunaration] VARCHAR (50) NULL,
CONSTRAINT [PK_Journal] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Ledger] FOREIGN KEY ([drac]) REFERENCES [dbo].[Ledger] ([Id]) ON DELETE CASCADE ON UPDATE CASCADE
);
Ledger table:
CREATE TABLE [dbo].[Ledger]
(
[Id] DECIMAL (18) IDENTITY (1, 1) NOT NULL,
[name] NVARCHAR (50) NULL,
[type] NVARCHAR (50) NULL,
[classification] VARCHAR (50) NULL,
[realornominal] VARCHAR (50) NULL,
[reg_date] DATETIME NULL,
[last_update] DATETIME NULL,
[active] DECIMAL (2) NULL,
[depree] VARCHAR (50) NULL,
CONSTRAINT [PK_Ledger] PRIMARY KEY CLUSTERED ([Id] ASC)
);
In your current query, you're joining on J.drac = L.Id, which means that L will always be the record which is referenced in J.drac, regardless of the value of J.crac.
The way I understand it, you want to reference two different records in the Ledger table. You need two joins for that.
SELECT
J.Id, J.date, J.drac, D.name as draccount, J.crac,
C.name as craccount, J.dramt, J.cramt, J.lf,
J.description, J.voucherType, J.reg_date, J.last_update,
J.active
FROM Journal J
INNER JOIN Ledger D ON J.drac = D.Id
INNER JOIN Ledger C ON J.crac = C.Id

Problem with SQL syntax (probably simple)

I'm doing some custom database work for a module for Drupal and I get the following SQL error when trying to create my table:
user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT NULL, rooms INT DEFAULT NULL, adults INT DEFAULT NULL, children' at line 14 query: CREATE TABLE dr_enquiry ( eId INT unsigned NOT NULL auto_increment, eKey VARCHAR(16) NOT NULL, dateSent INT NOT NULL DEFAULT 0, status VARCHAR(30) NOT NULL DEFAULT 'Unanswered', custName VARCHAR(50) NOT NULL, custEmail VARCHAR(200) NOT NULL, custPhone VARCHAR(25) NOT NULL, custCountry VARCHAR(40) NOT NULL, custIP VARCHAR(11) DEFAULT NULL, offerName VARCHAR(100) NOT NULL, offerURL VARCHAR(200) NOT NULL, arrival DATETIME DEFAULT NULL, departure DEFAULT NULL, rooms INT DEFAULT NULL, adults INT DEFAULT NULL, children INT DEFAULT NULL, childAges VARCHAR(32) DEFAULT NULL, toddlers INT DEFAULT NULL, toddlerAges VARCHAR(32) DEFAULT NULL, catering VARCHAR(255) DEFAULT NULL, comments VARCHAR(255) DEFAULT NULL, agent VARCHAR(100) DEFAULT NULL, voucher VARCHAR(100) DEFAULT NULL, PRIMARY KEY (eId) ) /*!40100 DEFAULT CHARACTER SET UTF8 */ in /home/travelco/public_html/includes/database.inc on line 550.
The 'departure' field doesn't seem to have a type eg varchar, mediumint etc. Try adding one and see if that solves your problem :)
Nullability is not set using a DEFAULT constraint. Thus, the compiler is balking at each instance of DEFAULT NULL. Thus, the create statement should look like:
CREATE TABLE dr_enquiry (
eId INT unsigned NOT NULL auto_increment
, eKey VARCHAR(16) NOT NULL
, dateSent INT NOT NULL DEFAULT 0
, status VARCHAR(30) NOT NULL DEFAULT 'Unanswered'
, custName VARCHAR(50) NOT NULL
, custEmail VARCHAR(200) NOT NULL
, custPhone VARCHAR(25) NOT NULL
, custCountry VARCHAR(40) NOT NULL
, custIP VARCHAR(11) NULL
, offerName VARCHAR(100) NOT NULL
, offerURL VARCHAR(200) NOT NULL
, arrival DATETIME NULL
, departure DATETIME NULL
, rooms INT NULL
, adults INT NULL
, children INT NULL
, childAges VARCHAR(32) NULL
, toddlers INT NULL
, toddlerAges VARCHAR(32) NULL
, catering VARCHAR(255) NULL
, comments VARCHAR(255) NULL
, agent VARCHAR(100) NULL
, voucher VARCHAR(100) NULL
, PRIMARY KEY (eId)
)
(Oh and departure did not have a datatype as richsage mentioned. I presumed it was DateTime.)