I have Two Table in sql server 2008
TABLE [tblTagDescription](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[TopicID] [int] NULL,
[TagID] [int] NULL,
[FullTag] [nvarchar](50) NULL,
[ValDecimal] [nvarchar](50) NULL,
[ValBinary] [nvarchar](50) NULL,
[GroupName] [nvarchar](50) NULL,
[ReportTag] [nvarchar](50) NULL
)
And
TABLE [tblDataLog](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[TagDescID] [bigint] NULL,
[Value] [decimal](18, 2) NULL,
[Date] [datetime] NULL,
)
Here there might be same Group for multiple "Id" of tblDescription and "TagDescID" of tblDataLog.
Here 'Group1' has 10 ID as from 1 to 10. and there might be multiple record for these ID (from 1 to 10) in tbldatalog. I want these ID from 1 to as columns. I want Average of these ID (From 1 to 10).
For this I used pivot:
Declare #COls nvarchar(max)
Declare #SQL nvarchar(max)
DECLARE #COlsID NVARCHAR(MAX) = ''
DECLARE #COlsAlias NVARCHAR(MAX) = ''
IF OBJECT_ID('tempdb..##MYTABLE') IS NOT NULL DROP TABLE ##MYTABLE
IF OBJECT_ID('tempdb..#tt') IS NOT NULL DROP TABLE #tt
IF(#Group='A')
BEGIN
Select #COls=COALESCE(#Cols + '],[','') + z.ReportTag From
(Select Distinct T.ID, ReportTag From tblTagDescription T
Where isnull(ReportTag,'')<>'' AND T.GroupName=#Group Group BY T.ID,T.ReportTag --order by T.ID
)z
END
ELSE
BEGIN
SELECT
#COlsID = #ColsID + ',' + z.TagDescID,
#COlsAlias = #COlsAlias + ',' + z.TagDescID + ' AS ' + z.ReportTag
FROM
(select TagDescID,ReportTag from(SELECT DISTINCT TOP 50 QUOTENAME(CONVERT(NVARCHAR(25),
tblDataLog.TagDescID )) TagDescID,TagdescID TID,
QUOTENAME(tblTagDescription.ReportTag) ReportTag
FROM tblDataLog
INNER JOIN tblTagDescription ON tblDataLog.TagDescID = tblTagDescription.ID
where tblTagDescription.GroupName=#Group
ORDER BY tblDataLog.TagDescID )s
) z
END
SET #COlsID= STUFF(#COlsID,1,1,'')
SET #COlsAlias= STUFF(#COlsAlias,1,1,'')
SET #SQL='select [DATE],SHIFT, ' + #COlsAlias + ' into ##MYTABLE from ( select [Date], AVG(Value), TagDescID,
(CASE
WHEN ((DATEPART(hour,[DATE]))>6 and (DATEPART(hour,[DATE]))<14) THEN ''A''
WHEN ((DATEPART(hour,[DATE]))>=14 and (DATEPART(hour,[DATE]))<22) THEN ''B''
WHEN ((DATEPART(hour,[DATE]))>=22 or (DATEPART(hour,[DATE]))<6) THEN ''C''
END )AS SHIFT
from tblDataLog Group by [Date],[TagDescID] )d pivot(max(Value) for TagDescID in (' + #COlsID + ')) piv;'
EXEC (#SQL)
select * from ##MYTABLE
But the above query is giving error as :
Msg 8155, Level 16, State 2, Line 8
No column name was specified for column 2 of 'd'.
Msg 207, Level 16, State 1, Line 8
Invalid column name 'Value'.
Msg 208, Level 16, State 0, Procedure Select_DataViewer, Line 58
Invalid object name '##MYTABLE'.
How to solve this?
Related
I work on SQL Server 2014 and my issue occurred after displaying Feature Name and Feature Value separated by $.
When executing the query below after adding Feature Name and Feature Value with stuff it became very slow.
How to enhance it?
Before adding the two stuff statements it took 28 seconds to display 750 thousand records. Now as below script and after adding two stuff statements take 5 minutes.
Script below give me expected result but issue is performance is very slow.
So can I do separate Feature Name and Feature Value to make it faster? Separated by $ if possible.
My script:
IF OBJECT_ID('[dbo].[gen]') IS NOT NULL
DROP TABLE [dbo].[gen]
IF OBJECT_ID('[dbo].[PartAttributes]') IS NOT NULL
DROP TABLE [dbo].[PartAttributes]
IF OBJECT_ID('dbo.core_datadefinition_Detailes') IS NOT NULL
DROP TABLE core_datadefinition_Detailes
CREATE TABLE core_datadefinition_Detailes
(
[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[ColumnName] [nvarchar](500) NOT NULL,
[ColumnNumber] [int] NOT NULL,
CONSTRAINT [PK_Core_DataDefinition_Details]
PRIMARY KEY CLUSTERED ([ID] ASC)
)
INSERT INTO core_datadefinition_Detailes([ColumnNumber],[ColumnName])
VALUES (202503, 'Product Shape Type'),
(1501170111, 'Type'),
(202504, 'Package Family')
CREATE TABLE [dbo].[gen]
(
[TradeCodeControlID] [int] IDENTITY(1,1) NOT NULL,
[CodeTypeID] [int] NULL,
[RevisionID] [bigint] NULL,
[Code] [varchar](20) NULL,
[ZPLID] [int] NULL,
[ZfeatureKey] [bigint] NULL,
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[gen] ON
INSERT INTO [dbo].[gen] ([TradeCodeControlID], [CodeTypeID],[RevisionID], [Code], [ZPLID], [ZfeatureKey])
VALUES (7565, 849774, 307683692, N'8541100050', 4239, 202503)
INSERT INTO [dbo].[gen] ([TradeCodeControlID], [CodeTypeID],[RevisionID], [Code], [ZPLID], [ZfeatureKey])
VALUES (7566, 849774, 307683692, N'8541100050', 4239, 202504)
INSERT INTO [dbo].[gen] ([TradeCodeControlID], [CodeTypeID],[RevisionID], [Code], [ZPLID], [ZfeatureKey])
VALUES (7567, 849774, 307683692, N'8541100050', 4239, 1501170111)
SET IDENTITY_INSERT [dbo].[gen] OFF
CREATE TABLE [dbo].[PartAttributes]
(
[PartID] [int] NOT NULL,
[ZfeatureKey] [bigint] NULL,
[AcceptedValuesOption_Value] [float] NULL,
[FeatureValue] [nvarchar](500) NOT NULL
) ON [PRIMARY]
GO
INSERT INTO [dbo].[PartAttributes] ([PartID], [ZfeatureKey], [FeatureValue])
VALUES (413989, 202503, N'Discrete')
INSERT INTO [dbo].[PartAttributes] ([PartID], [ZfeatureKey], [FeatureValue])
VALUES (413989, 1501170111, N'Zener')
INSERT INTO [dbo].[PartAttributes] ([PartID], [ZfeatureKey], [FeatureValue])
VALUES (413989, 202504, N'SOT')
SELECT
PartID, Code, Co.CodeTypeID, Co.RevisionID, Co.ZPLID,
COUNT(1) AS ConCount,
STUFF((SELECT '$' + CAST(CP.ColumnName AS VARCHAR(300)) AS [text()]
FROM
(SELECT DISTINCT
d.ColumnName, C.codeTypeId, C.Code, C.ZfeatureKey
FROM gen C
INNER JOIN core_datadefinitiondetails d WITH (NOLOCK) ON C.ZfeatureKey = d.columnnumber
INNER JOIN PartAttributes P ON P.partid = PM.partid) CP
WHERE CP.codeTypeId = Co.codeTypeId AND CP.Code = Co.Code
ORDER BY CP.ZfeatureKey
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS FeatureName,
STUFF((SELECT '$' + CAST(CP2.FeatureValue AS VARCHAR(300)) AS [text()]
FROM
(SELECT DISTINCT
P.FeatureValue, C2.codeTypeId, C2.Code, C2.ZfeatureKey
FROM gen C2
INNER JOIN PartAttributes P ON C2.ZfeatureKey = P.ZfeatureKey) CP2
WHERE CP2.codeTypeId = Co.codeTypeId AND CP2.Code = Co.Code
ORDER BY CP2.ZfeatureKey
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS FeatureValue
FROM
PartAttributes PM
INNER JOIN
gen Co ON Co.ZfeatureKey = PM.ZfeatureKey
GROUP BY
PartID, Code, Co.CodeTypeID, Co.RevisionID, Co.ZPLID
Final result:
final result after add two stuff
I am having an issue with a dynamic query to pivot on an unknown number of columns in MS SQL server 2014. I've based my query on the article SQL Server 2005 Pivot on Unknown Number of Columns and other similar articles. However, I am having two issues that I can't decipher.
When executing the dynamic SQL, I get this error:
The name 'SELECT Code, LastName, FirstName, [03-30-2021],[06-30-2021],[08-00-2021],[10-30-2021],[12-30-2021],[17-30-2021],[18-30-2021],[19-30-2021],[20-30-2021],[21-30-2021],[22-30-2021],[24-30-2021],[25-30-2021],[26-30-2021],[29-30-2021] FROM (
SELECT i.Code, aa.LastName, aa.FirstName, FORMAT(StartDate, 'dd-mm-yyyy') AS StartDate, FORMAT(s.SignOut-s.SignIn, 'hh:mm') AS AttendanceTime
FROM ActualSession AS a INNER JOIN ActualAttendee aa ON( a.id = aa.ActualSessionId)
INNER JOIN Attendee att ON (att.Id = aa.AttendeeId)
LEFT JOIN SignIn s ON (a.Id = s.ActualSessionId) LEFT JOIN Identification i ON (i.AttendeeId = aa.AttendeeId
AND i.Id' is not a valid identifier.
However, if I copy and paste the query into a separate window in SQL Server Management Studio, it runs... I can't see what is wrong, except that the error message is only returning the first xxx characters of the query... Any suggestions as to what I have done wrong would be appreciated. Is it the joins, or the way I've selected columns?
BUT... that takes me to the second issue. When I do run the copied query text separately, it works but it is showing the same values (time in hours/minutes) for all users, rather than the user-specific values (though users who did not sign in are correctly coming up NULL). The pivot seems to need a min/max/other aggregate, but where it should be keeping it to each user (according to what I can see, by some SQL voodoo), it's not... The column names also appear to be coming up in US date format, even though I've specified the format as Australian (dd-mm-yyyy). If anyone knows how to correct these issues, that would also be appreciated.
Code LastName FirstName 03-30-2021 06-30-2021 08-00-2021 10-30-2021
abc123 Simpson Homer 01:07 01:15 NULL 01:01
abc456 Griffen Peter 01:07 01:15 NULL 01:01
abc789 Flintsone Fred 01:07 01:15 NULL 01:01
xyz123 Heffernan Doug 01:07 01:15 NULL 01:01
xyz456 Gergich Jerry NULL NULL NULL NULL
xyz789 Kramden Ralph 01:07 01:15 NULL 01:01
The full query I am running is:
#Query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT DISTINCT '],[' + FORMAT(StartDate, 'dd-mm-yyyy') FROM ActualSession
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,2,'') + ']'
SET #Query = 'SELECT Code, LastName, FirstName, ' + #cols + ' FROM (
SELECT i.Code, aa.LastName, aa.FirstName, FORMAT(StartDate, ''dd-mm-yyyy'') AS StartDate, FORMAT(s.SignOut-s.SignIn, ''hh:mm'') AS AttendanceTime
FROM ActualSession AS a INNER JOIN ActualAttendee aa ON( a.id = aa.ActualSessionId)
INNER JOIN Attendee att ON (att.Id = aa.AttendeeId)
LEFT JOIN SignIn s ON (a.Id = s.ActualSessionId) LEFT JOIN Identification i ON (i.AttendeeId = aa.AttendeeId
AND i.IdentificationTypeId = (SELECT Id FROM IdentificationType WHERE [Name] = ''Student Code''))
) x PIVOT ( max(AttendanceTime)
FOR StartDate in (' + #cols + ') ) p '
PRINT #Query --for debugging
execute #Query
Relevant Table definitions are:
CREATE TABLE [dbo].[ActualSession](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[EventId] [bigint] NOT NULL,
[EventName] [nvarchar](50) NOT NULL,
[EventSessionId] [bigint] NOT NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
[Active] [bit] NULL,
[SignInRequired] [bit] NULL,
[SignOutRequired] [bit] NULL,
[SignInAllowed] [bit] NULL,
[SignOutAllowed] [bit] NULL,
[EarlySignInAllowed] [bit] NULL,
[EarlySignOutAllowed] [bit] NULL,
[LateSignInAllowed] [bit] NULL,
[LateSignOutAllowed] [bit] NULL,
[ExpiredIdAllowed] [bit] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Attendee](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[PreferredName] [nvarchar](50) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[SignIn](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[EventId] [bigint] NOT NULL,
[ActualSessionId] [bigint] NOT NULL,
[AttendeeId] [bigint] NOT NULL,
[SignIn] [datetime] NOT NULL,
[SignOut] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Identification](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[AttendeeId] [bigint] NOT NULL,
[IdentificationTypeId] [bigint] NOT NULL,
[Code] [nvarchar](50) NOT NULL,
[ExpiryDate] [date] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[IdentificationType](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[RevHex] [bit] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ActualAttendee](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[EventId] [bigint] NOT NULL,
[ActualSessionId] [bigint] NOT NULL,
[AttendeeId] [bigint] NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[PreferredName] [nvarchar](50) NULL,
[GroupId] [bigint] NULL,
[GroupName] [nvarchar](50) NULL,
[GroupTypeId] [bigint] NULL,
[GroupTypeName] [nvarchar](50) NULL,
[GroupTypeAD] [bit] NULL,
[GroupTypeADName] [nvarchar](200) NULL,
[GroupTypeDB] [bit] NULL,
[GroupTypeDBQuery] [nvarchar](1000) NULL,
[GroupTypeManual] [bit] NULL
) ON [PRIMARY]
GO
You have two issues here:
Your main issue: when you call execute you need to enclose #Query in parenthesis (). I suggest, though, that you use sp_executesql, because this enables you to pass through parameters if necessary
Your second problem: don't try to quote the column names yourself, use QUOTENAME
DECLARE #Query AS nvarchar(MAX), #cols nvarchar(MAX);
SELECT #cols = STUFF((
SELECT DISTINCT ',' + QUOTENAME(FORMAT(StartDate, 'dd-mm-yyyy'))
FROM ActualSession
FOR XML PATH(''), TYPE
).value('text()[1]', 'NVARCHAR(MAX)')
, 1, LEN(','), '');
SET #Query = '
SELECT
Code,
LastName,
FirstName,
' + #cols + '
FROM (
SELECT
i.Code,
aa.LastName,
aa.FirstName,
FORMAT(StartDate, ''dd-mm-yyyy'') AS StartDate,
FORMAT(s.SignOut-s.SignIn, ''hh:mm'') AS AttendanceTime
FROM ActualSession AS a
INNER JOIN ActualAttendee aa ON (a.id = aa.ActualSessionId)
INNER JOIN Attendee att ON (att.Id = aa.AttendeeId)
LEFT JOIN SignIn s ON (a.Id = s.ActualSessionId)
LEFT JOIN Identification i ON (i.AttendeeId = aa.AttendeeId
AND i.IdentificationTypeId = (SELECT Id FROM IdentificationType WHERE [Name] = ''Student Code''))
) x
PIVOT ( max(AttendanceTime)
FOR StartDate in (
' + #cols + '
) ) p;
';
PRINT #Query --for debugging
EXEC sp_executesql #Query;
I believe the error you are receiving is related to the usage of execute #Query instead of execute (#Query). Looking at the Microsoft doc on EXECUTE, executing a string variable requires open and close parens:
Execute a character string
{ EXEC | EXECUTE }
( { #string_variable | [ N ]'tsql_string' } [ + ...n ] )
[ AS { LOGIN | USER } = ' name ' ]
[;]
Once I added the parens, I was able to get what I believe is an equivalent statement to yours to execute as expected with some sample data I created.
As for your date format, I believe your date format string has an issue. I believe your current date format string of dd-mm-yyyy is meant to be dd-MM-yyyy. Per the Custom date and time format strings Microsoft doc (referenced by Microsoft doc on FORMAT):
"mm" The minute, from 00 through 59.
"MM" The month, from 01 through 12.
I have a school management system. I just created a stored procedure for retrieving a list of students from the database. If I just pass in null to all parameters, the stored procedure works fine, but when I add some parameter values, then I get this error:
Msg 50000, Level 15, State 1, Procedure GetStudentList, Line 91
Incorrect syntax near the keyword 'and'
Here is my stored procedure code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetStudentList]
(#rollno VARCHAR(5) = NULL,
#name VARCHAR(25)= NULL,
#classid INT = NULL,
#sectionid INT = NULL)
AS
DECLARE #qry NVARCHAR(MAX)
DECLARE #sql NVARCHAR(MAX)
DECLARE #rollcond NVARCHAR(5)
DECLARE #namecond NVARCHAR(25)
DECLARE #classcond NVARCHAR(10)
DECLARE #sectioncond NVARCHAR(10)
BEGIN
BEGIN TRY
SET #qry = N'select PK_PID as ID,
StudentName as Name
,Gender
,FatherName as Parents
,Address
,format(DOB,''dd/MM/yyyy'') as DOB
,EmailID
,AdmissionDate
,(select [ClassName] from dbo.classes where classes.PK_PID = s.Class) AS Class
,(select [SectionName] from dbo.sections where sections.PK_PID = s.Section) AS Section
,RollNo
,MobileNo
,Active
,StudentPhoto
from dbo.students s where 1=1'
IF #rollno is null
BEGIN
SET #rollcond = ''
END
ELSE
BEGIN
SET #rollcond = ' and s.RollNo like ''%'+#rollno+'%'' '
END
IF #name IS NULL
BEGIN
SET #namecond = ''
END
ELSE
BEGIN
SET #namecond = ' and s.StudentName like ''%'+#name+'%'' '
END
IF #classid IS NULL
BEGIN
SET #classcond = ''
END
ELSE
BEGIN
SET #classcond =' and s.Class = '+CONVERT(INT,#classid)+' '
END
IF #sectionid IS NULL
BEGIN
SET #sectioncond = ''
END
ELSE
BEGIN
SET #sectioncond =' and s.Section = '+CONVERT(INT,#sectionid)+' '
END
SET #sql = #qry + #rollcond + #namecond + #classcond + #sectioncond
--+' order by ID asc '
EXEC sp_executesql #sql
END TRY
BEGIN CATCH
DECLARE #ErrorMessage NVARCHAR(4000);
DECLARE #ErrorSeverity INT;
DECLARE #ErrorState INT;
SELECT
#ErrorMessage = ERROR_MESSAGE(),
#ErrorSeverity = ERROR_SEVERITY(),
#ErrorState = ERROR_STATE();
RAISERROR (#ErrorMessage, -- Message text.
#ErrorSeverity, -- Severity.
#ErrorState); -- State.
END CATCH;
END
What's going wrong here? Please guys help me...
----------------updated------------------------
USE [SM_00001]
GO
/****** Object: StoredProcedure [dbo].[GetStudentList] Script Date: 11/7/2019 8:56:52 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetStudentList]
(
#searchtext varchar(200) = null,
#classid int = null,
#sectionid int = null
)
AS
BEGIN
--new script
select [PK_PID] as ID,
[StudentName] as Name
,[Gender]
,[FatherName] as Parents
,[Address]
,format([DOB],'dd/MM/yyyy') as DOB
,[EmailID]
,[AdmissionDate]
,C.[ClassName] as Class
,Section.[SectionName] as Section
,[RollNo]
,[MobileNo]
,[Active]
,[StudentPhoto]
from [dbo].[students] as s
outer apply (select isnull([ClassName],'Default Class') from [dbo].[classes] where [classes].[PK_PID] = s.[Class]) as C
outer apply (select isnull([SectionName],'Default Section') from [dbo].[sections] where [sections].[PK_PID] = s.[Section]) as Section
where (#searchtext is null or s.[StudentName] LIKE '%'+#searchtext+'%'
or s.[Gender] LIKE '%'+#searchtext+'%'
or s.[FatherName] LIKE '%'+#searchtext+'%'
or s.[Address] LIKE '%'+#searchtext+'%'
or s.[DOB] LIKE '%'+#searchtext+'%'
or s.[Address] LIKE '%'+#searchtext+'%'
or s.[MobileNo] LIKE '%'+#searchtext+'%'
or s.[EmailID] LIKE '%'+#searchtext+'%')
and (#classid is null or s.[Class] = CONVERT(INT,#classid))
and (#sectionid is null or s.[Section] = CONVERT(INT,#sectionid))
--old script
--select PK_PID as ID,
-- StudentName as Name
-- ,Gender
-- ,FatherName as Parents
-- ,Address
-- ,format(DOB,'dd/MM/yyyy') as DOB
-- ,EmailID
-- ,AdmissionDate
-- ,(select [ClassName] from dbo.classes where classes.PK_PID = s.Class) AS Class
-- ,(select [SectionName] from dbo.sections where sections.PK_PID = s.Section) AS Section
-- ,RollNo
-- ,MobileNo
-- ,Active
-- ,StudentPhoto
--from dbo.students s order by ID asc
END
i just get sql error here :
Msg 8155, Level 16, State 2, Procedure GetStudentList, Line 36
No column name was specified for column 1 of 'C'.
Msg 8155, Level 16, State 2, Procedure GetStudentList, Line 38
No column name was specified for column 1 of 'Section'.
Msg 207, Level 16, State 1, Procedure GetStudentList, Line 27
Invalid column name 'ClassName'.
Msg 207, Level 16, State 1, Procedure GetStudentList, Line 28
Invalid column name 'SectionName'.
-----------------------update 2--------------------------
CREATE TABLE [dbo].[students](
[PK_PID] [int] IDENTITY(1,1) NOT NULL,
[StudentName] [varchar](25) NULL,
[Gender] [varchar](10) NULL,
[FatherName] [varchar](25) NULL,
[MotherName] [varchar](25) NULL,
[DOB] [datetime] NULL,
[Religion] [varchar](15) NULL,
[BloodGroup] [varchar](5) NULL,
[FatherOccupation] [varchar](25) NULL,
[EmailID] [varchar](150) NULL,
[AdmissionDate] [datetime] NULL,
[AdmissionID] [varchar](25) NULL,
[Class] [int] NULL,
[Section] [int] NULL,
[RollNo] [varchar](5) NULL,
[Address] [varchar](200) NULL,
[BIO] [varchar](200) NULL,
[MobileNo] [varchar](15) NULL,
[PhoneNo] [varchar](15) NULL,
[Active] [bit] NULL,
[Entry_By] [int] NULL,
[Enty_date] [smalldatetime] NULL CONSTRAINT [DF_students_Enty_date] DEFAULT (getdate()),
[StudentPhoto] [image] NULL,
CONSTRAINT [PK_students] PRIMARY KEY CLUSTERED
(
[PK_PID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
CREATE TABLE [dbo].[classes](
[PK_PID] [int] IDENTITY(1,1) NOT NULL,
[ClassName] [varchar](25) NULL,
[Entry_By] [int] NULL,
[Entry_Date] [smalldatetime] NULL CONSTRAINT [DF_classes_Entry_Date] DEFAULT (getdate()),
CONSTRAINT [PK_classes] PRIMARY KEY CLUSTERED
(
[PK_PID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[sections](
[PK_PID] [int] IDENTITY(1,1) NOT NULL,
[SectionName] [varchar](10) NULL,
[Entry_By] [int] NULL,
[Entry_Date] [smalldatetime] NULL CONSTRAINT [DF_sections_Entry_Date] DEFAULT (getdate()),
CONSTRAINT [PK_sections] PRIMARY KEY CLUSTERED
(
[PK_PID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
This is a far better way to write your query, that does not use dynamic sql:
select PK_PID as ID,
StudentName as Name
,Gender
,FatherName as Parents
,Address
,format(DOB,'dd/MM/yyyy') as DOB
,EmailID
,AdmissionDate
,(select [ClassName] from dbo.classes where classes.PK_PID = s.Class) AS Class
,(select [SectionName] from dbo.sections where sections.PK_PID = s.Section) AS Section
,RollNo
,MobileNo
,Active
,StudentPhoto
from dbo.students s
where (#rollno is null or s.RollNo like '%'+#rollno+'%' )
and (#name is null or s.StudentName like '%'+#name+'%')
and (#classid is null or s.Class = CONVERT(INT,#classid))
and (#sectionid is null or s.Section = CONVERT(INT,#sectionid))
You can also go with outer apply instead of 'inline query'
For more details Click here
Also, refer here some concepts Click here
This is a far better way to write your query, that does not use dynamic SQL:
Here your stored procedure code:
CREATE PROCEDURE [dbo].[GetStudentList]
(#searchtext VARCHAR(200) = NULL,
#classid INT = NULL,
#sectionid INT = NULL)
AS
BEGIN
SELECT
[PK_PID] as ID,
[StudentName] as Name,
[Gender],
[FatherName] as Parents,
[Address],
FORMAT([DOB], 'dd/MM/yyyy') AS DOB,
[EmailID],
[AdmissionDate],
C.[ClassName] AS Class,
Section.[SectionName] AS Section,
[RollNo], [MobileNo], [Active], [StudentPhoto]
FROM
[dbo].[students] AS s
OUTER APPLY
(SELECT
ISNULL([ClassName], 'Default Class') AS ClassName
FROM
[dbo].[classes]
WHERE
[classes].[PK_PID] = s.[Class]) AS C
OUTER APPLY
(SELECT ISNULL([SectionName], 'Default Section') AS SectionName
FROM [dbo].[sections]
WHERE [sections].[PK_PID] = s.[Section]) AS Section
WHERE
(#searchtext IS NULL OR
s.[StudentName] LIKE '%' + #searchtext + '%' OR
s.[Gender] LIKE '%' + #searchtext + '%' OR
s.[FatherName] LIKE '%' + #searchtext + '%' OR
s.[Address] LIKE '%' + #searchtext + '%' OR
s.[DOB] LIKE '%' + #searchtext + '%' OR
s.[Address] LIKE '%' + #searchtext + '%' OR
s.[MobileNo] LIKE '%' + #searchtext + '%' OR
s.[EmailID] LIKE '%' + #searchtext + '%')
AND (#classid IS NULL OR s.[Class] = CONVERT(INT, #classid))
AND (#sectionid IS NULL OR s.[Section] = CONVERT(INT, #sectionid))
END
Here is your query that you want it
SELECT [PK_PID] AS ID,
[StudentName] AS Name
,[Gender]
,[FatherName] AS Parents
,[Address]
,FORMAT([DOB],'dd/MM/yyyy') AS DOB
,[EmailID]
,[AdmissionDate]
,C.[ClassName] AS Class
,Section.[SectionName] AS Section
,[RollNo]
,[MobileNo]
,[Active]
,[StudentPhoto]
FROM [dbo].[students] AS s
outer apply (select isnull([ClassName],'Default Class') AS ClassName from [dbo].[classes] where [classes].[PK_PID] = s.[Class]) as C
outer apply (select isnull([SectionName],'Default Section') AS SectionName from [dbo].[sections] where [sections].[PK_PID] = s.[Section]) as Section
WHERE (#rollno IS NULL OR s.[RollNo] LIKE '%'+#rollno+'%' )
AND (#name IS NULL OR s.[StudentName] LIKE '%'+#name+'%')
AND (#classid IS NULL OR s.[Class] = CONVERT(INT,#classid))
AND (#sectionid IS NULL OR s.[Section] = CONVERT(INT,#sectionid))
I have a table created as follows:
CREATE TABLE [1M].[FLOWERS](
[utcDT] [datetime2](7) NOT NULL,
[Symbol] [nvarchar](50) NULL,
[Open] [float] NULL,
[High] [float] NULL,
[Low] [float] NULL,
[Close] [float] NULL
) ON [PRIMARY]
How can I create a table such that I get a column for each different [Symbol] and value in column is the [Close] grouped by [utcDT]
Assume there are 10 different symbols.
I want:
utcDT,Symbol1,Symbol2,...,Symbol10
10:23,1.1 ,1.2 ,...,1.07
10:24,1.3 ,1.2 ,...,1.09
10:25,1.2 ,1.3 ,...,1.10
In Excel this is easily done with a pivot table. How can I achieve this in SQL?
You can use this.
SELECT [utcDT], [1] Symbol1 ,[2] Symbol2,[3] Symbol3,[4] Symbol4,[5] Symbol5,[6] Symbol6,[7] Symbol7,[8] Symbol8,[9] Symbol9,[10] Symbol10 FROM (
SELECT CAST([utcDT] AS time) [utcDT] , [Close], [Symbol] FROM FLOWERS ) SRC
PIVOT( MAX( [Close]) FOR [Symbol] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10])) PVT
If you want to make it dynamically you can use this.
DECLARE #ColNamesForPivot VARCHAR(MAX) = ''
DECLARE #ColNamesForSelect VARCHAR(MAX) = ''
SELECT
#ColNamesForPivot = #ColNamesForPivot + ', ' + QUOTENAME([Symbol])
,#ColNamesForSelect = #ColNamesForSelect + ', '+ QUOTENAME([Symbol]) + ' '+ QUOTENAME('Symbol' + CONVERT(VARCHAR,[Symbol]))
FROM FLOWERS
GROUP BY [Symbol]
DECLARE #SqlQ NVARCHAR(MAX) =
'SELECT [utcDT] ' + #ColNamesForSelect + ' FROM (
SELECT CAST([utcDT] AS time) [utcDT] , [Close], [Symbol] FROM FLOWERS ) SRC
PIVOT( MAX([Close]) FOR [Symbol] IN (' + STUFF(#ColNamesForPivot,1,1,'') + ')) PVT'
EXEC(#SqlQ)
You could use conditional aggregation:
SELECT utcDT
,MIN(CASE WHEN Symbol = 'Symbol1' THEN [Close] END) AS Symbol1
--,...
,MIN(CASE WHEN Symbol = 'Symbol10' THEN [Close] END) AS Symbol10
FROM tab
GROUP BY utcDT
ORDER BY utcDT;
In my select statement, the column DisplayStatus is a computed column that significantly slows down the performance.
I tried to make it PERSISTENT but it tells me that table need to be dropped and recreated again. I cannot do that, I am not the owner of those tables.
Scalar function (pretty complex) is responsible for computed column.
My select statement:
declare
#EffDateFrom datetime ='2017-02-01',
#EffDateTo datetime ='2017-08-28'
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb..#Data') IS NOT NULL
DROP TABLE #Data
CREATE TABLE #Data
(
QuoteID int NOT NULL,
[EffectiveDate] [datetime] NULL,
[Submitted] [int] NULL,
[Quoted] [int] NULL,
[Bound] [int] NULL,
[Exonerated] [int] NULL,
[ProducerLocationId] [int] NULL,
[ProducerName] [varchar](300) NULL,
[BusinessType] [varchar](50) NULL,
[DisplayStatus] [varchar](50) NULL, --This is the problem
[Agent] [varchar] (50) NULL,
[ProducerContactGuid] uniqueidentifier NULL
)
INSERT INTO #Data
SELECT
tblQuotes.QuoteID,
tblQuotes.EffectiveDate,
CASE
WHEN lstQuoteStatus.QuoteStatusID >= 1
THEN 1
ELSE 0
END AS Submitted,
CASE
WHEN lstQuoteStatus.QuoteStatusID = 2 OR
lstQuoteStatus.QuoteStatusID = 3 OR
lstQuoteStatus.QuoteStatusID = 202
THEN 1
ELSE 0
END AS Quoted,
CASE WHEN lstQuoteStatus.Bound = 1 THEN 1 ELSE 0 END AS Bound,
CASE WHEN lstQuoteStatus.QuoteStatusID = 3 THEN 1 ELSE 0 END AS Exonareted,
tblQuotes.ProducerLocationID,
P.Name + ' / '+ P.City as [ProducerName],
CASE
WHEN tblQuotes.PolicyTypeID = 1 THEN 'New Business'
WHEN tblQuotes.PolicyTypeID = 3 THEN 'Rewrite'
END AS BusinessType,
tblQuotes.DisplayStatus, -------------This is the problem
tblProducerContacts.FName +' '+ tblProducerContacts.LName as Agent,
tblProducerContacts.ProducerContactGUID
FROM
tblQuotes
INNER JOIN
lstQuoteStatus ON tblQuotes.QuoteStatusID = lstQuoteStatus.QuoteStatusID
INNER JOIN
tblProducerLocations P ON P.ProducerLocationID = tblQuotes.ProducerLocationID
INNER JOIN
tblProducerContacts ON dbo.tblQuotes.ProducerContactGuid = tblProducerContacts.ProducerContactGUID
WHERE
tblQuotes.EffectiveDate >= #EffDateFrom
AND tblQuotes.EffectiveDate <= #EffDateTo
AND dbo.tblQuotes.LineGUID = '6E00868B-FFC3-4CA0-876F-CC258F1ED22D'--Surety
AND tblQuotes.OriginalQuoteGUID IS NULL
SELECT * FROM #Data
Is any other workaround to bring this column without slowing down the performance?
Execution Plan: