How to optimize sql multiple select queries? - sql

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.

Related

What is wrong with this access query?

Running the below query returns 0 records, but I would expect it to return 3.
SELECT
ID,
DW2_TV_DimStation_Id,
DW2_OTT_DimStation_Id,
Name,
CoreTVCode,
CoreOTTCode,
StrataTVCode,
HouseHolds,
MaleSkew,
FemaleSkew,
AverageAge,
AverageIncome,
BroadReach,
Description,
Owner,
Notes,
timestamp,
CreatedOn,
ModifiedOn,
Retired,
1 AS Accepted
FROM
Planning_DimStation AS src
WHERE
src.[timestamp] = (
SELECT
MAX([timestamp])
FROM
Planning_DimStation AS src2
WHERE
src2.[ID] = src.[ID]
)
AND NOT EXISTS (
SELECT
1
FROM
DimStation AS tgt
WHERE
tgt.[ID] = src.[ID]
);
The part that breaks it is the NOT EXISTS statement. If I delete the NOT EXISTS it works fine.
Table 1: Planning_DimStation
Is an SQL table linked with 3 records in it. Source below.
Table 2: DimStation
Is an Access table (pic of source UI below) that is empty
Could this be a silent fail caused by type missmatch?
Table 1:
CREATE TABLE [Planning].[DimStation]
(
[ID] INT PRIMARY KEY,
[DW2_TV_DimStation_Id] INT NULL,
[DW2_OTT_DimStation_Id] INT NULL,
[Name] NVARCHAR(128) NOT NULL,
[CoreTVCode] CHAR(5) NULL,
[CoreOTTCode] CHAR(10) NULL,
[StrataTVCode] CHAR(10) NULL,
[HouseHolds] DECIMAL(5,2) NULL,
[MaleSkew] DECIMAL(5,2) NULL,
[FemaleSkew] DECIMAL(5,2) NULL,
[AverageAge] INT NULL,
[AverageIncome] DECIMAL(23,2) NULL,
[BroadReach] BIT NULL,
[Description] NVARCHAR(MAX) NULL,
[Owner] NVARCHAR(128) NULL,
[Notes] NVARCHAR(MAX) NULL,
[timestamp] timestamp NOT NULL,
[CreatedOn] DATETIME2(7) CONSTRAINT [df_Planning_DimStation_CreatedOn] DEFAULT (sysutcdatetime()) NOT NULL,
[ModifiedOn] DATETIME2(7) CONSTRAINT [df_Planning_DimStation_ModifiedOn] DEFAULT (sysutcdatetime()) NOT NULL,
[Retired] BIT CONSTRAINT [df_Planning_DimStation_Retired] DEFAULT (0) NOT NULL
)
GO
Table 2:
Joining on different data types tends to yield unexpected results.
To fix this, use casts.
A note is that Access doesn't allow nulls to be cast. So we need to work around that using Nz (same as ISNULL in T-SQL) and explicitly handling nulls.
AND NOT EXISTS (
SELECT
1
FROM
DimStation AS tgt
WHERE
CLng(IIF(tgt.[ID] IS NULL, 0, tgt.ID)) = src.[ID] AND NOT tgt.ID IS NULL
);

SQL Server - Operand type clash: numeric is incompatible with datetimeoffset

i am having issue with passing the data from one table to another due to data type.
I tried converting datetimeoffset into date, and inserting into table where i have it as date type and im still getting this error.
this is the format of date/time i have:
2018-12-12 13:00:00 -05:00 in one table, and i have to just pars time and insert it into new table. I tried with casting using ,
CAST([from] AS date) DATE_FROM
I can run the query as select and it works but the moment i try to insert the data into other table even if the other table is formatted and prepared as date type i still get the issue.
Here is the table that stored data with datetimeoffset:
[dbo].[tmp_count](
[elements_Id] [numeric](20, 0) NULL,
[content_Id] [numeric](20, 0) NULL,
[element_Id] [numeric](20, 0) NULL,
[element-name] [nvarchar](255) NULL,
[sensor-type] [nvarchar](255) NULL,
[data-type] [nvarchar](255) NULL,
[from] [datetimeoffset](0) NULL,
[to] [datetimeoffset](0) NULL,
[measurements_Id] [numeric](20, 0) NULL,
[measurement_Id] [numeric](20, 0) NULL,
[from (1)] [datetimeoffset](0) NULL,
[to (1)] [datetimeoffset](0) NULL,
[values_Id] [numeric](20, 0) NULL,
[label] [nvarchar](255) NULL,
[text] [tinyint] NULL
And I am trying to cast columns with datetimeoffset to date and time and push it to #tmp1 table with
SELECT [elements_Id]
,[content_Id]
,[element_Id]
,[element-name]
,[sensor-type]
,[data-type]
,CAST([from] AS date) DATE_FROM
,[to]
,[measurements_Id]
,[measurement_Id]
,CAST([from (1)] AS time (0)) TIME_FROM
,CAST([to (1)] AS TIME(0)) TIME_TO
,[values_Id]
,[label]
,[text]
INTO #Tmp1
FROM [VHA].[dbo].[tmp_count]
SELECT
FROM #tmp1
which gives me the time in format for DATE_FROM as 2018-12-12 and for the DATE_FROM and DATE_TO as 13:00:00 which is exactly what i need.
Now i am trying to splice this table with another table and push it in final table that looks like this:
[dbo].[tbl_ALL_DATA_N](
[serial-number] [nvarchar](255) NULL,
[ip-address] [nvarchar](255) NULL,
[name] [nvarchar](255) NULL,
[group] [nvarchar](255) NULL,
[device-type] [nvarchar](255) NULL,
[elements_Id] [numeric](20, 0) NULL,
[content_Id] [numeric](20, 0) NULL,
[element_Id] [numeric](20, 0) NULL,
[element-name] [nvarchar](255) NULL,
[sensor-type] [nvarchar](255) NULL,
[data-type] [nvarchar](255) NULL,
[DATE_FROM] [date] NULL,
[to] [datetimeoffset](0) NULL,
[measurements_Id] [numeric](20, 0) NULL,
[measurement_Id] [numeric](20, 0) NULL,
[TIME_FROM] [time](0) NULL,
[TIME_TO] [time](0) NULL,
[values_Id] [numeric](20, 0) NULL,
[label] [nvarchar](255) NULL,
[text] [tinyint] NULL
using query below:
INSERT INTO [dbo].[tbl_ALL_DATA_N]
([serial-number],
[ip-address],
[name],
[group],
[device-type],
[measurement_id],
TIME_FROM,
TIME_TO,
[content_id],
[elements_id],
[element-name],
[sensor-type],
[data-type],
DATE_FROM,
[to],
[element_id],
[measurements_id],
[values_id],
[label],
[text])
SELECT *
FROM [VHA].[dbo].[tmp_sensor_info] A
FULL OUTER JOIN #tmp1 B
ON 1 = 1
And here is another message im getting: Msg 206, Level 16, State 2, Line 25
Operand type clash: numeric is incompatible with time
Any ideas?
The solution, which #PanagiotisKanavos alluded to in the comments, is to explicitly list the columns in your final SELECT * FROM.... The order of the columns in that SELECT statement aren't lining up with the columns you're INSERTing into in the destination table.
You may need to run an ad hoc instance of the query to sort out the column order. And then do yourself a favor for future maintenance and be sure to include a table alias on all of the listed columns so you (or whoever has to look at the code next) can easily find out if data is coming from [VHA].[dbo].[tmp_sensor_info] or #tmp1.
This is just one of many dangers in using SELECT * in production code. There's a ton of discussion on the issue in this question: Why is SELECT * considered harmful?
Also, as long as you're in there fixing up the query, consider meaningful table aliases. See: Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3).

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

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

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

Error converting data type varchar to bigint in stored procedure

I'm trying to call this procedure with the usp_TimesheetsAuditsLoadAllbyId 42747, NULL command.
But I always get an error
Msg 8114, Level 16, State 5, Procedure usp_TimesheetsAuditsLoadAllById, Line 9
Error converting data type varchar to bigint.
The ID of TimesheetsAudits table is a bigint type. I tried several types of conversions and casts, but I'm really stuck right now.
Hope somebody can help. Thanks
ALTER PROCEDURE [dbo].[usp_TimesheetsAuditsLoadAllById]
(
#Id INT,
#StartDate DATETIME
)
AS
BEGIN
SET NOCOUNT ON
SELECT TOP 51 *
FROM
(SELECT TOP 51
ID,
Type,
ReferrerId,
CAST(Description AS VARCHAR(MAX)) AS Description,
OnBehalfOf,
Creator,
DateCreated
FROM
TimesheetsAudits
WHERE
(ReferrerID = #Id) AND
(#StartDate IS NULL OR DateCreated < #StartDate)
ORDER BY
DateCreated DESC
UNION
SELECT TOP 51
tia.ID,
tia.Type,
tia.ReferrerId,
'[Day: ' + CAST(DayNr AS VARCHAR(5)) + '] ' + CAST(tia.Description AS VARCHAR(MAX)) AS Description,
tia.OnBehalfOf,
tia.Creator,
tia.DateCreated
FROM
TimesheetItemsAudits tia
INNER JOIN
TimesheetItems ti ON tia.ReferrerId = ti.ID
WHERE
(ti.TimesheetID = #Id) AND
(#StartDate IS NULL OR tia.DateCreated < #StartDate)
ORDER BY
tia.DateCreated DESC) t
ORDER BY
t.DateCreated DESC
END
Table definition for tables from comments:
CREATE TABLE [dbo].[TimesheetsAudits](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Type] [tinyint] NOT NULL,
[ReferrerId] [varchar](15) NOT NULL,
[Description] [text] NULL,
[OnBehalfOf] [varchar](10) NULL,
[Creator] [varchar](10) NOT NULL,
[DateCreated] [datetime] NOT NULL
)
CREATE TABLE [dbo].[TimesheetItemsAudits](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Type] [tinyint] NOT NULL,
[ReferrerId] [varchar](15) NOT NULL,
[Description] [text] NULL,
[OnBehalfOf] [varchar](10) NULL,
[Creator] [varchar](10) NOT NULL,
[DateCreated] [datetime] NOT NULL
)
You perform an INNER JOIN of [dbo].[TimesheetsAudits] and TimesheetItems ti ON tia.ReferrerId = ti.ID
tia.[ReferrerId] is varchar and ti.[ID] is [bigint].
I'd expect a value in tia.[ReferrerId] that cannot be converted to bigint.
Try the following:
SELECT [ReferrerId] FROM TimesheetItemsAudits WHERE ISNUMERIC(ReferrerId) = 0
This may help you to find the "offending rows".