Slowness when submitting form - dotnetnuke

We are seeing some fairly extreme (I would call it extreme) slowness of around 20 seconds when submitting a form on our DNN website using 2sxc forms.
The issue appears to be that on every single form submit, 2sxc executes around 20 or so SQL statements in the background, one of which takes between 8 and 13 seconds to run every single time. The rest of them take less than 100 ms. The query can be seen below.
I have tried re-indexing the DB, didn't help. I'd like to find out why this query is running and maybe how I can turn it off or do anything to increase performance.
SELECT
[UnionAll1].[EntityID] AS [C1],
[UnionAll1].[AttributeSetID] AS [C2],
[UnionAll1].[AttributeSetID1] AS [C3],
[UnionAll1].[ChangeID] AS [C4],
[UnionAll1].[C2] AS [C5],
[UnionAll1].[EntityID1] AS [C6],
[UnionAll1].[EntityGUID] AS [C7],
[UnionAll1].[AttributeSetID2] AS [C8],
[UnionAll1].[C3] AS [C9],
[UnionAll1].[AssignmentObjectTypeID] AS [C10],
[UnionAll1].[KeyGuid] AS [C11],
[UnionAll1].[KeyNumber] AS [C12],
[UnionAll1].[KeyString] AS [C13],
[UnionAll1].[IsPublished] AS [C14],
[UnionAll1].[PublishedEntityId] AS [C15],
[UnionAll1].[Owner] AS [C16],
[UnionAll1].[Timestamp] AS [C17],
[UnionAll1].[C1] AS [C18],
[UnionAll1].[AttributeID] AS [C19],
[UnionAll1].[AttributeID1] AS [C20],
[UnionAll1].[C4] AS [C21],
[UnionAll1].[ChildEntityID] AS [C22],
[UnionAll1].[C5] AS [C23],
[UnionAll1].[C6] AS [C24],
[UnionAll1].[C7] AS [C25],
[UnionAll1].[C9] AS [C26],
[UnionAll1].[C10] AS [C27],
[UnionAll1].[C11] AS [C28],
[UnionAll1].[C12] AS [C29],
[UnionAll1].[C13] AS [C30],
[UnionAll1].[C14] AS [C31],
[UnionAll1].[C15] AS [C32],
[UnionAll1].[C16] AS [C33],
[UnionAll1].[C17] AS [C34]
FROM (SELECT
CASE WHEN ([Join3].[AttributeID1] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1],
[Project1].[EntityID] AS [EntityID],
[Project1].[AttributeSetID1] AS [AttributeSetID],
[Project1].[AttributeSetID1] AS [AttributeSetID1],
[Project1].[ChangeID] AS [ChangeID],
[Project1].[C1] AS [C2],
[Project1].[EntityID] AS [EntityID1],
[Project1].[EntityGUID] AS [EntityGUID],
[Project1].[AttributeSetID] AS [AttributeSetID2],
[Project1].[C1] AS [C3],
[Project1].[AssignmentObjectTypeID] AS [AssignmentObjectTypeID],
[Project1].[KeyGuid] AS [KeyGuid],
[Project1].[KeyNumber] AS [KeyNumber],
[Project1].[KeyString] AS [KeyString],
[Project1].[IsPublished] AS [IsPublished],
[Project1].[PublishedEntityId] AS [PublishedEntityId],
[Project1].[Owner] AS [Owner],
[Project1].[Timestamp] AS [Timestamp],
[Join3].[AttributeID1] AS [AttributeID],
[Join3].[AttributeID1] AS [AttributeID1],
CASE WHEN ([Join3].[AttributeID1] IS NULL) THEN CAST(NULL AS int) WHEN ([Join3].[AttributeID2] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C4],
[Join3].[ChildEntityID] AS [ChildEntityID],
[Join3].[SortOrder] AS [SortOrder],
CAST(NULL AS int) AS [C5],
CAST(NULL AS int) AS [C6],
CAST(NULL AS int) AS [C7],
CAST(NULL AS int) AS [C8],
CAST(NULL AS int) AS [C9],
CAST(NULL AS int) AS [C10],
CAST(NULL AS varchar(1)) AS [C11],
CAST(NULL AS int) AS [C12],
CAST(NULL AS int) AS [C13],
CAST(NULL AS int) AS [C14],
CAST(NULL AS int) AS [C15],
CAST(NULL AS bit) AS [C16],
CAST(NULL AS varchar(1)) AS [C17]
FROM (SELECT
[Filter1].[EntityID] AS [EntityID],
[Filter1].[EntityGUID] AS [EntityGUID],
[Filter1].[AttributeSetID1] AS [AttributeSetID],
[Filter1].[AssignmentObjectTypeID] AS [AssignmentObjectTypeID],
[Filter1].[KeyNumber] AS [KeyNumber],
[Filter1].[KeyGuid] AS [KeyGuid],
[Filter1].[KeyString] AS [KeyString],
[Filter1].[IsPublished] AS [IsPublished],
[Filter1].[PublishedEntityId] AS [PublishedEntityId],
[Filter1].[Owner] AS [Owner],
[Filter1].[AttributeSetID2] AS [AttributeSetID1],
[Extent3].[ChangeID] AS [ChangeID],
[Extent3].[Timestamp] AS [Timestamp],
1 AS [C1]
FROM (SELECT [Extent1].[EntityID] AS [EntityID], [Extent1].[EntityGUID] AS [EntityGUID], [Extent1].[AttributeSetID] AS [AttributeSetID1], [Extent1].[AssignmentObjectTypeID] AS [AssignmentObjectTypeID], [Extent1].[KeyNumber] AS [KeyNumber], [Extent1].[KeyGuid] AS [KeyGuid], [Extent1].[KeyString] AS [KeyString], [Extent1].[IsPublished] AS [IsPublished], [Extent1].[PublishedEntityId] AS [PublishedEntityId], [Extent1].[ChangeLogModified] AS [ChangeLogModified], [Extent1].[Owner] AS [Owner], [Extent2].[AttributeSetID] AS [AttributeSetID2], [Extent2].[AppID] AS [AppID]
FROM [dbo].[ToSIC_EAV_Entities] AS [Extent1]
INNER JOIN [dbo].[ToSIC_EAV_AttributeSets] AS [Extent2] ON [Extent1].[AttributeSetID] = [Extent2].[AttributeSetID]
WHERE ([Extent1].[ChangeLogDeleted] IS NULL) AND ([Extent2].[ChangeLogDeleted] IS NULL) ) AS [Filter1]
LEFT OUTER JOIN [dbo].[ToSIC_EAV_ChangeLog] AS [Extent3] ON [Filter1].[ChangeLogModified] = [Extent3].[ChangeID]
WHERE ([Filter1].[AppID] = #p__linq__0) AND (#p__linq__1 <> cast(1 as bit)) ) AS [Project1]
OUTER APPLY (SELECT [Distinct1].[AttributeID] AS [AttributeID1], [Extent5].[AttributeID] AS [AttributeID2], [Extent5].[ChildEntityID] AS [ChildEntityID], [Extent5].[SortOrder] AS [SortOrder]
FROM (SELECT DISTINCT
[Extent4].[AttributeID] AS [AttributeID]
FROM [dbo].[ToSIC_EAV_EntityRelationships] AS [Extent4]
WHERE [Project1].[EntityID] = [Extent4].[ParentEntityID] ) AS [Distinct1]
LEFT OUTER JOIN [dbo].[ToSIC_EAV_EntityRelationships] AS [Extent5] ON ([Project1].[EntityID] = [Extent5].[ParentEntityID]) AND ([Distinct1].[AttributeID] = [Extent5].[AttributeID]) ) AS [Join3]
UNION ALL
SELECT
2 AS [C1],
[Project4].[EntityID] AS [EntityID],
[Project4].[AttributeSetID1] AS [AttributeSetID],
[Project4].[AttributeSetID1] AS [AttributeSetID1],
[Project4].[ChangeID] AS [ChangeID],
[Project4].[C1] AS [C2],
[Project4].[EntityID] AS [EntityID1],
[Project4].[EntityGUID] AS [EntityGUID],
[Project4].[AttributeSetID] AS [AttributeSetID2],
[Project4].[C1] AS [C3],
[Project4].[AssignmentObjectTypeID] AS [AssignmentObjectTypeID],
[Project4].[KeyGuid] AS [KeyGuid],
[Project4].[KeyNumber] AS [KeyNumber],
[Project4].[KeyString] AS [KeyString],
[Project4].[IsPublished] AS [IsPublished],
[Project4].[PublishedEntityId] AS [PublishedEntityId],
[Project4].[Owner] AS [Owner],
[Project4].[Timestamp] AS [Timestamp],
CAST(NULL AS int) AS [C4],
CAST(NULL AS int) AS [C5],
CAST(NULL AS int) AS [C6],
CAST(NULL AS int) AS [C7],
CAST(NULL AS int) AS [C8],
[Join8].[AttributeID3] AS [AttributeID],
[Join8].[AttributeID3] AS [AttributeID1],
CASE WHEN ([Join8].[ValueID1] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C9],
[Join8].[ChangeLogCreated] AS [ChangeLogCreated],
[Join8].[ValueID1] AS [ValueID],
[Join8].[ValueID1] AS [ValueID1],
[Join8].[Value] AS [Value],
[Join8].[ChangeLogCreated] AS [ChangeLogCreated1],
CASE WHEN ([Join8].[ValueID1] IS NULL) THEN CAST(NULL AS int) WHEN ([Join8].[ValueID2] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C10],
[Join8].[DimensionID1] AS [DimensionID],
[Join8].[DimensionID1] AS [DimensionID1],
[Join8].[ReadOnly] AS [ReadOnly],
CASE WHEN ([Join8].[ValueID1] IS NULL) THEN CAST(NULL AS varchar(1)) WHEN ([Join8].[ValueID2] IS NULL) THEN CAST(NULL AS varchar(1)) ELSE LOWER([Join8].[ExternalKey]) END AS [C11]
FROM (SELECT
[Filter4].[EntityID] AS [EntityID],
[Filter4].[EntityGUID] AS [EntityGUID],
[Filter4].[AttributeSetID3] AS [AttributeSetID],
[Filter4].[AssignmentObjectTypeID] AS [AssignmentObjectTypeID],
[Filter4].[KeyNumber] AS [KeyNumber],
[Filter4].[KeyGuid] AS [KeyGuid],
[Filter4].[KeyString] AS [KeyString],
[Filter4].[IsPublished] AS [IsPublished],
[Filter4].[PublishedEntityId] AS [PublishedEntityId],
[Filter4].[Owner] AS [Owner],
[Filter4].[AttributeSetID4] AS [AttributeSetID1],
[Extent8].[ChangeID] AS [ChangeID],
[Extent8].[Timestamp] AS [Timestamp],
1 AS [C1]
FROM (SELECT [Extent6].[EntityID] AS [EntityID], [Extent6].[EntityGUID] AS [EntityGUID], [Extent6].[AttributeSetID] AS [AttributeSetID3], [Extent6].[AssignmentObjectTypeID] AS [AssignmentObjectTypeID], [Extent6].[KeyNumber] AS [KeyNumber], [Extent6].[KeyGuid] AS [KeyGuid], [Extent6].[KeyString] AS [KeyString], [Extent6].[IsPublished] AS [IsPublished], [Extent6].[PublishedEntityId] AS [PublishedEntityId], [Extent6].[ChangeLogModified] AS [ChangeLogModified], [Extent6].[Owner] AS [Owner], [Extent7].[AttributeSetID] AS [AttributeSetID4], [Extent7].[AppID] AS [AppID]
FROM [dbo].[ToSIC_EAV_Entities] AS [Extent6]
INNER JOIN [dbo].[ToSIC_EAV_AttributeSets] AS [Extent7] ON [Extent6].[AttributeSetID] = [Extent7].[AttributeSetID

There are a few things you can do, but specifically 2sxc 9.30 is much, much much faster at saving, because it does a partial cache-update only.
Otherwise rebuilding your indexes on your DB usually also helps a lot.

Related

Different Output between Stored Procedure and Direct Query

I have a Stored Procedure that has been working fine for about 8 months of use in preparing data to be sent off to another service. Two days ago it started truncating the results but there hasn't been any changes to the code in that time period.
Here's the weird part, if I take the statements out of the stored procedure and don't change anything other than making it a direct query, I get the expected result.
Stored Procedure: 5481 Rows
Direct Query: 7490 Rows
I've tried dropping the execution cache, bouncing the server and services but that doesn't fix it. I have also setup a temporary table to capture any of the prepared batches within the Stored Procedure to compare against the direct query and those all match.
I'm at a loss as to how this is even possible.
Edit:
Code Added Here
CREATE PROCEDURE [ETL].[spDeliverTransactionalFile]
#TransactionDate DATE
,#MonthNum INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FiscalPeriodShort VARCHAR(10)
,#FiscalQuarterShort VARCHAR(9)
,#CalendarMonth INT
CREATE TABLE #MonthNum (
FiscalPeriodShort VARCHAR(10)
,MaxDate DATE
,MonthNum INT
)
IF #TransactionDate IS NULL OR #TransactionDate = '2006-12-31'
BEGIN
INSERT INTO #MonthNum
SELECT FiscalPeriodShort
,MAX(DateID) AS MaxDate
,ROW_NUMBER() OVER (ORDER BY MAX(DateID) ASC) AS MonthNum
FROM dimDate
WHERE FiscalQuarterShort = (
SELECT FiscalQuarterShort
FROM dimDate
WHERE DateID = dbo.TransactionDateID(NULL)
)
GROUP BY FiscalPeriodShort
END
ELSE
BEGIN
INSERT INTO #MonthNum
SELECT FiscalPeriodShort
,MAX(DateID) AS MaxDate
,ROW_NUMBER() OVER (ORDER BY MAX(DateID) ASC) AS MonthNum
FROM dimDate
WHERE FiscalQuarterShort = (
SELECT FiscalQuarterShort
FROM dimDate
WHERE DateID = #TransactionDate
)
GROUP BY FiscalPeriodShort
END
SELECT #FiscalPeriodShort = FiscalPeriodShort
FROM #MonthNum
WHERE MonthNum = #MonthNum
SELECT #CalendarMonth = MIN(CalendarMonth)
FROM dimDate
WHERE FiscalPeriodShort = #FiscalPeriodShort
SELECT CONVERT(VARCHAR(20),l.OrderId) AS OrderCode
,CONVERT(VARCHAR(10),ROW_NUMBER() OVER (PARTITION BY l.OrderID ORDER BY dp.Model, dr.RebateID)) + '-' + CONVERT(VARCHAR(10),l.factBookingLineSID) AS ItemCode
,'Sell' + #FiscalPeriodShort + '_' + CONVERT(VARCHAR(2),#CalendarMonth) AS BatchName
,'Sell' AS BatchType
,REPLACE(REPLACE(dp.Model, ', ', '-'), ',', '-') AS ProductName
,REPLACE(REPLACE(dst.SalesTeamName, ', ', '-'), ',', '-') AS GeographyName
,REPLACE(REPLACE(dc.CustomerName, ', ', '-'), ',', '-') AS CustomerName
,SUM(l.CurrentUnitQuantity) AS Quantity
,SUM(l.CurrentLineTotal) AS Amount
,'USD' AS AmountUnitType
,CONVERT(VARCHAR(10),dd.DateID,101) AS IncentiveDate
,'Sell' AS OrderType
,dst.SalesTeamID
,CASE WHEN dp.ProductGroupCode NOT IN ('Prod1','Prod2','Prod3','Prod4') THEN 'Group1'
WHEN dp.ProductGroupCode = 'Prod3' AND l.FranchiseSID IN (1,3) THEN 'Group1'
WHEN dp.ProductGroupCode = 'Prod4' AND l.FranchiseSID IN (1,3) THEN 'Group1'
WHEN dp.ProductGroupCode IN ('Prod1','Prod2') THEN 'Group2'
WHEN dp.ProductGroupCode = 'Prod3' AND l.FranchiseSID = 2 THEN 'Group2'
WHEN dp.ProductGroupCode = 'Prod4' AND l.FranchiseSID = 2 THEN 'Group2'
ELSE 'UKWN'
END AS Product_Type
FROM factTransactionLine l
INNER JOIN dimDate dd ON l.TransactionDateSID = dd.DateSID
INNER JOIN dimProduct dp ON l.ProductLotSID = dp.ProductLotSID
INNER JOIN dimSalesTeam dst ON l.CurrentSalesTeamSID = dst.SalesTeamSID
INNER JOIN dimCustomer dc ON l.CustomerSID = dc.CustomerSID
WHERE l.Deleted = 0
AND dd.FiscalPeriodShort = #FiscalPeriodShort
GROUP BY l.OrderId
,dp.PartNumber
,dp.Model
,dc.CustomerName
,dd.DateID
,dst.SalesTeamName
,dst.SalesTeamID
,dp.ProductGroupCode
,l.FranchiseSID
,l.factTransactionLineSID
ORDER BY OrderCode
,ItemCode
DROP TABLE #MonthNum
END
At Which Point I am running the Stored Procedure using the following syntax:
EXEC etl.spDeliverTransactionalFile #TransactionDate = '2018-03-14', #MonthNum = 1
Which returns 5481 Rows.
But If I take the Query out of the Stored Procedure as follows:
DECLARE #TransactionDate DATE
,#MonthNum INT
SELECT #TransactionDate = '2018-03-14'
,#MonthNum = 1
DECLARE #FiscalPeriodShort VARCHAR(10)
,#FiscalQuarterShort VARCHAR(9)
,#CalendarMonth INT
CREATE TABLE #MonthNum (
FiscalPeriodShort VARCHAR(10)
,MaxDate DATE
,MonthNum INT
)
IF #TransactionDate IS NULL OR #TransactionDate = '2006-12-31'
BEGIN
INSERT INTO #MonthNum
SELECT FiscalPeriodShort
,MAX(DateID) AS MaxDate
,ROW_NUMBER() OVER (ORDER BY MAX(DateID) ASC) AS MonthNum
FROM dimDate
WHERE FiscalQuarterShort = (
SELECT FiscalQuarterShort
FROM dimDate
WHERE DateID = dbo.TransactionDateID(NULL)
)
GROUP BY FiscalPeriodShort
END
ELSE
BEGIN
INSERT INTO #MonthNum
SELECT FiscalPeriodShort
,MAX(DateID) AS MaxDate
,ROW_NUMBER() OVER (ORDER BY MAX(DateID) ASC) AS MonthNum
FROM dimDate
WHERE FiscalQuarterShort = (
SELECT FiscalQuarterShort
FROM dimDate
WHERE DateID = #TransactionDate
)
GROUP BY FiscalPeriodShort
END
SELECT #FiscalPeriodShort = FiscalPeriodShort
FROM #MonthNum
WHERE MonthNum = #MonthNum
SELECT #CalendarMonth = MIN(CalendarMonth)
FROM dimDate
WHERE FiscalPeriodShort = #FiscalPeriodShort
SELECT CONVERT(VARCHAR(20),l.OrderId) AS OrderCode
,CONVERT(VARCHAR(10),ROW_NUMBER() OVER (PARTITION BY l.OrderID ORDER BY dp.Model, dr.RebateID)) + '-' + CONVERT(VARCHAR(10),l.factBookingLineSID) AS ItemCode
,'Sell' + #FiscalPeriodShort + '_' + CONVERT(VARCHAR(2),#CalendarMonth) AS BatchName
,'Sell' AS BatchType
,REPLACE(REPLACE(dp.Model, ', ', '-'), ',', '-') AS ProductName
,REPLACE(REPLACE(dst.SalesTeamName, ', ', '-'), ',', '-') AS GeographyName
,REPLACE(REPLACE(dc.CustomerName, ', ', '-'), ',', '-') AS CustomerName
,SUM(l.CurrentUnitQuantity) AS Quantity
,SUM(l.CurrentLineTotal) AS Amount
,'USD' AS AmountUnitType
,CONVERT(VARCHAR(10),dd.DateID,101) AS IncentiveDate
,'Sell' AS OrderType
,dst.SalesTeamID
,CASE WHEN dp.ProductGroupCode NOT IN ('Prod1','Prod2','Prod3','Prod4') THEN 'Group1'
WHEN dp.ProductGroupCode = 'Prod3' AND l.FranchiseSID IN (1,3) THEN 'Group1'
WHEN dp.ProductGroupCode = 'Prod4' AND l.FranchiseSID IN (1,3) THEN 'Group1'
WHEN dp.ProductGroupCode IN ('Prod1','Prod2') THEN 'Group2'
WHEN dp.ProductGroupCode = 'Prod3' AND l.FranchiseSID = 2 THEN 'Group2'
WHEN dp.ProductGroupCode = 'Prod4' AND l.FranchiseSID = 2 THEN 'Group2'
ELSE 'UKWN'
END AS Product_Type
FROM factTransactionLine l
INNER JOIN dimDate dd ON l.TransactionDateSID = dd.DateSID
INNER JOIN dimProduct dp ON l.ProductLotSID = dp.ProductLotSID
INNER JOIN dimSalesTeam dst ON l.CurrentSalesTeamSID = dst.SalesTeamSID
INNER JOIN dimCustomer dc ON l.CustomerSID = dc.CustomerSID
WHERE l.Deleted = 0
AND dd.FiscalPeriodShort = #FiscalPeriodShort
GROUP BY l.OrderId
,dp.PartNumber
,dp.Model
,dc.CustomerName
,dd.DateID
,dst.SalesTeamName
,dst.SalesTeamID
,dp.ProductGroupCode
,l.FranchiseSID
,l.factTransactionLineSID
ORDER BY OrderCode
,ItemCode
DROP TABLE #MonthNum
I will get the correct data at 7490 rows.
This
SELECT FiscalQuarterShort
FROM dimDate
WHERE DateID = dbo.TransactionDateID(NULL)
Is non-deterministic
Why not just reassign #TransactionDate rather than repeat all that code?
So it turns out to be a Fully Qualified issue.
There was another table added under another schema for dimProduct at some point. When running the query as is, it was defaulting to dbo. When running it under the stored procedure it was running it under the alternate schema which is used for ETL.
I always thought that if a schema wasn't defined the Query Engine would default to dbo, but that wasn't the case here.

Returning Rows Created in a Cursor From a Stored Procedure

I have a table with three columns each containing comma separated data like
AAA,BBB,CCC,DDD,....
I want to return a CROSS JOIN with all the possible combinations of all the tokens from all columns, along with some of the other columns on each row.
I have a Split function which returns the tokens in a table. I pass in each column and get a bunch of rows back.
The best way I have been able to come up with to do this is with a cursor, taking each row one at a time. After doing the CROSS JOIN, I write all the calculated rows to a work/temp table. Once all the rows are processed, I SELECT from the work/temp table to return the calculated rows.
My question: Is there a way to do this without the work/temp table?
The code I have now is:
DECLARE cPKG CURSOR FAST_FORWARD FOR SELECT ID, SEARCH, COUNTY, COMPANY FROM DEV..EXPPKG WITH(NOLOCK)
OPEN cPKG
FETCH NEXT FROM cPKG INTO #ID, #SEARCH, #COUNTY, #COMPANY
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO DEV..PKG_DUMP_WORK
(ID,
PKG_CODE,
PRICE,
CNTY,
CPNY,
SRCH,
SEARCH,
COUNTY,
COMPANY,
SRCH_COUNT,
UPDT_DT,
UPDT_BY,
UPDT_CMT)
SELECT PKG.ID,
PKG.PKG_CODE,
PKG.PRICE,
CNTY.VALUE AS CNTY,
CPNY.VALUE AS CPNY,
SRCH.VALUE AS SRCH,
PKG.SEARCH,
PKG.COUNTY,
PKG.COMPANY,
PKG.SRCH_COUNT,
PKG.UPDT_DT,
PKG.UPDT_BY,
PKG.UPDT_CMT
FROM (SELECT *
FROM DEV..EXPPKG WITH(NOLOCK)
WHERE ID = #ID) PKG
CROSS JOIN DBO.Split(#SEARCH, ',') SRCH -- AAA,BBB,CCC...
CROSS JOIN DBO.Split(#COUNTY, ',') CNTY -- DDD,EEE,FFF..
CROSS JOIN DBO.Split(#COMPANY, ',') CPNY -- GGG,HHH,KKK...
FETCH NEXT FROM cPKG INTO #ID, #SEARCH, #COUNTY, #COMPANY
END
CLOSE cPKG
DEALLOCATE cPKG
Some data:
INSERT INTO [EXPPKG] ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'A-2', 999, 'CO,ER,FC,HB,ST,TX', 'BX,KG,QN,RI', ',AAN,ALR,CITI,GRANITE,HARB,LLS,LTTA,MADI,NARROW,REGENCY,', 6, NULL, NULL, NULL );
INSERT INTO [EXPPKG] ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'AM-2', 999, 'CO,ER,FC,HB,ST,TX', 'MA', ',ALR,CITI,GRANITE,INTER,LTTA,MADI,SKYLINE,', 6, NULL, NULL, NULL );
INSERT INTO [EXPPKG] ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'B-2', 999, 'AR,CO,ER,FC,HB,HI,HL,ST,TX', 'BX,KG,QN,RI', ',C&C,LTTA,', 9, NULL, NULL, NULL );
INSERT INTO [EXPPKG] ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'CA-2', 999, 'CO,ER,FC,HB,HI,ST,TX', 'BX,KG,MA,QN,RI', ',CANY,CHATHAM,TRAK,', 7, NULL, NULL, NULL );
INSERT INTO [EXPPKG] ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'CT-4', 999, 'CO,ER,FC,HB', 'BX,KG,MA,QN,RI', ',CLTLTNY,CTALB,CTIM,CTIM-711,CTIM-CC,CTIM-Q,CTIM-R,CTIMR-O,FNT,FNT-A,FNT-AG,FNT-N,FNT-R,NYLS,TICOR,TICORROC,FNT-RAM,', 4, NULL, NULL, NULL );
You could replace the entire cursor with a set based insert. I would also caution you against using that NOLOCK hint. It can and will return missing and/or duplicate rows. Along with a number of other nasty things. http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/
INSERT INTO DEV..PKG_DUMP_WORK
(
ID,
PKG_CODE,
PRICE,
CNTY,
CPNY,
SRCH,
SEARCH,
COUNTY,
COMPANY,
SRCH_COUNT,
UPDT_DT,
UPDT_BY,
UPDT_CMT
)
SELECT PKG.ID,
PKG.PKG_CODE,
PKG.PRICE,
CNTY.VALUE AS CNTY,
CPNY.VALUE AS CPNY,
SRCH.VALUE AS SRCH,
PKG.SEARCH,
PKG.COUNTY,
PKG.COMPANY,
PKG.SRCH_COUNT,
PKG.UPDT_DT,
PKG.UPDT_BY,
PKG.UPDT_CMT
FROM DEV..EXPPKG PKG WITH(NOLOCK)
CROSS APPLY DBO.Split(PKG.SEARCH, ',') SRCH -- AAA,BBB,CCC...
CROSS APPLY DBO.Split(PKG.COUNTY, ',') CNTY -- DDD,EEE,FFF..
CROSS APPLY DBO.Split(PKG.COMPANY, ',') CPNY -- GGG,HHH,KKK...
Try to use CROSS APPLY
SELECT *
FROM DEV..EXPPKG WITH(NOLOCK)
CROSS APPLY DBO.Split(SEARCH, ',') SRCH -- AAA,BBB,CCC...
CROSS APPLY DBO.Split(COUNTY, ',') CNTY -- DDD,EEE,FFF..
CROSS APPLY DBO.Split(COMPANY, ',') CPNY
This is the solution using a generic Split function
DROP FUNCTION SplitString
GO
CREATE FUNCTION SplitString
(
#Input NVARCHAR(MAX),
#Character CHAR(1)
)
RETURNS #Output TABLE (
Value NVARCHAR(1000)
)
AS
BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output(Value)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
GO
declare #EXPPKG table ( ID int identity, PKG_CODE varchar(5) , PRICE int , SEARCH varchar(255), COUNTY varchar(255), COMPANY varchar(255), SRCH_COUNT varchar(255), UPDT_DT varchar(255), UPDT_BY varchar(255), UPDT_CMT varchar(255))
INSERT INTO #EXPPKG ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'A-2', 999, 'CO,ER,FC,HB,ST,TX', 'BX,KG,QN,RI', ',AAN,ALR,CITI,GRANITE,HARB,LLS,LTTA,MADI,NARROW,REGENCY,', 6, NULL, NULL, NULL );
INSERT INTO #EXPPKG ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'AM-2', 999, 'CO,ER,FC,HB,ST,TX', 'MA', ',ALR,CITI,GRANITE,INTER,LTTA,MADI,SKYLINE,', 6, NULL, NULL, NULL );
INSERT INTO #EXPPKG ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'B-2', 999, 'AR,CO,ER,FC,HB,HI,HL,ST,TX', 'BX,KG,QN,RI', ',C&C,LTTA,', 9, NULL, NULL, NULL );
INSERT INTO #EXPPKG ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'CA-2', 999, 'CO,ER,FC,HB,HI,ST,TX', 'BX,KG,MA,QN,RI', ',CANY,CHATHAM,TRAK,', 7, NULL, NULL, NULL );
INSERT INTO #EXPPKG ( PKG_CODE, PRICE, SEARCH, COUNTY, COMPANY, SRCH_COUNT, UPDT_DT, UPDT_BY, UPDT_CMT ) VALUES ( 'CT-4', 999, 'CO,ER,FC,HB', 'BX,KG,MA,QN,RI', ',CLTLTNY,CTALB,CTIM,CTIM-711,CTIM-CC,CTIM-Q,CTIM-R,CTIMR-O,FNT,FNT-A,FNT-AG,FNT-N,FNT-R,NYLS,TICOR,TICORROC,FNT-RAM,', 4, NULL, NULL, NULL );
Select
select
PKG.ID,
PKG.PKG_CODE,
PKG.PRICE,
SRCH.Value AS CNTY,
CPNY.Value CPNY,
SRCH.Value AS SRCH,
PKG.SEARCH,
PKG.COUNTY,
PKG.COMPANY,
PKG.SRCH_COUNT,
PKG.UPDT_DT,
PKG.UPDT_BY,
PKG.UPDT_CMT
from #EXPPKG PKG
CROSS APPLY DBO.SplitString(SEARCH, ',') SRCH
CROSS APPLY DBO.SplitString(COUNTY, ',') CNTY
CROSS APPLY DBO.SplitString(COMPANY, ',') CPNY
Result

Loop for extracting attributes of elements XML

I need to extract all attributes from a long list of various elements. Therefore, I'm seeking to build a loop going through all of my elements and return their attributes.
Through several posts I have been able to write the code below. However, I have more than a 1000 elements why I would extremely glad if it somehow is possible to build a loop around the latter part rather than copying it for all elements.
with cte as
(
select cast(
'<schema fwRel="2">
<taxFormId isPrimeKey="true" fkRef="C1-TXFRM" mapField="TAX_FORM_ID" dataType="string"/>
<formType fkRef="C1-FRMTY" mapField="FORM_TYPE_CD" dataType="string"/>
<bo suppress="true" required="true" fkRef="F1-BUSOB" mapField="BUS_OBJ_CD" dataType="string"/>
<transferReason mdField="C1_TXF_TFRRSN_FLG" dataType="lookup" mapXML="BO_DATA_AREA" lookup="C1_TXF_TFRRSN_FLG"/>
</schema>' as xml) xml_col
)
select cte.xml_col.value('(/schema/taxFormId/#fkRef)[1]', 'varchar(100)') as Dummy1
cte.xml_col.value('(/schema/taxFormId/#mapField)[1]', 'varchar(100)') as Dummy2
cte.xml_col.value('(/schema/taxFormId/#dataType)[1]', 'varchar(100)') as Dummy3
cte.xml_col.value('(/schema/taxFormId/#mapXML)[1]', 'varchar(100)') as Dummy4
from cte
I hope I have provided enough information
An easy way to get attributes listed:
with cte as
(
select cast(
'<schema fwRel="2">
<taxFormId isPrimeKey="true" fkRef="C1-TXFRM" mapField="TAX_FORM_ID" dataType="string" />
<formType fkRef="C1-FRMTY" mapField="FORM_TYPE_CD" dataType="string" />
<bo suppress="true" required="true" fkRef="F1-BUSOB" mapField="BUS_OBJ_CD" dataType="string" />
<transferReason mdField="C1_TXF_TFRRSN_FLG" dataType="lookup" mapXML="BO_DATA_AREA" lookup="C1_TXF_TFRRSN_FLG" />
</schema>' as xml) xml_col
)
--The query uses .nodes(N'/schema/*') to list all nodes below <schema> and .nodes(N'#*') to list all attributes within this node:
select nd.value(N'local-name(.)',N'nvarchar(max)') AS NodeName
,attr.value(N'local-name(.)',N'nvarchar(max)') AS AttrName
,attr.value(N'.',N'nvarchar(max)') AS AttrValue
from cte
OUTER APPLY xml_col.nodes(N'/schema/*') AS A(nd)
OUTER APPLY A.nd.nodes(N'#*') AS B(attr)
The result:
taxFormId isPrimeKey true
taxFormId fkRef C1-TXFRM
taxFormId mapField TAX_FORM_ID
taxFormId dataType string
formType fkRef C1-FRMTY
formType mapField FORM_TYPE_CD
formType dataType string
bo suppress true
bo required true
bo fkRef F1-BUSOB
bo mapField BUS_OBJ_CD
bo dataType string
transferReason mdField C1_TXF_TFRRSN_FLG
transferReason dataType lookup
transferReason mapXML BO_DATA_AREA
transferReason lookup C1_TXF_TFRRSN_FLG
If you need a statement like the one in your example one could create it dynamically (as string) and use EXEC to execute this (dynamic SQL).
It may be a little over-kill, but I often use a TVF to parse and hash large XML files. The function will return the data in a parent/child hierarchy structure with range keys R1/R2.
For example:
Declare #XML xml='
<schema fwRel="2">
<taxFormId isPrimeKey="true" fkRef="C1-TXFRM" mapField="TAX_FORM_ID" dataType="string"/>
<formType fkRef="C1-FRMTY" mapField="FORM_TYPE_CD" dataType="string"/>
<bo suppress="true" required="true" fkRef="F1-BUSOB" mapField="BUS_OBJ_CD" dataType="string"/>
<transferReason mdField="C1_TXF_TFRRSN_FLG" dataType="lookup" mapXML="BO_DATA_AREA" lookup="C1_TXF_TFRRSN_FLG"/>
</schema>'
Select * from [dbo].[udf-XML-Hier](#XML) Order by R1
Returns
You'll notice there are columns for Element Name, Attribute Name, XPath, Title (optional), and Value. The R1,R2,Lvl,ID and PT are all derived.
Being a TVF, you could apply any WHERE or ORDER desired
The UDF (with original source) if interested
CREATE FUNCTION [dbo].[udf-XML-Hier](#XML xml)
Returns Table
As Return
with cte0 as (
Select Lvl = 1
,ID = Cast(1 as int)
,Pt = Cast(NULL as int)
,Element = x.value('local-name(.)','varchar(150)')
,Attribute = cast('' as varchar(150))
,Value = x.value('text()[1]','varchar(max)')
,XPath = cast(concat(x.value('local-name(.)','varchar(max)'),'[' ,cast(Row_Number() Over(Order By (Select 1)) as int),']') as varchar(max))
,Seq = cast(10000001 as varchar(max))
,AttData = x.query('.')
,XMLData = x.query('*')
From #XML.nodes('/*') a(x)
Union All
Select Lvl = p.Lvl + 1
,ID = Cast( (Lvl + 1) * 1024 + (Row_Number() Over(Order By (Select 1)) * 2) as int ) * 10
,Pt = p.ID
,Element = c.value('local-name(.)','varchar(150)')
,Attribute = cast('' as varchar(150))
,Value = cast( c.value('text()[1]','varchar(max)') as varchar(max) )
,XPath = cast(concat(p.XPath,'/',c.value('local-name(.)','varchar(max)'),'[',cast(Row_Number() Over(PARTITION BY c.value('local-name(.)','varchar(max)') Order By (Select 1)) as int),']') as varchar(max) )
,Seq = cast(concat(p.Seq,' ',10000000+Cast( (Lvl + 1) * 1024 + (Row_Number() Over(Order By (Select 1)) * 2) as int ) * 10) as varchar(max))
,AttData = c.query('.')
,XMLData = c.query('*')
From cte0 p
Cross Apply p.XMLData.nodes('*') b(c)
)
, cte1 as (
Select R1 = Row_Number() over (Order By Seq),A.*
From (
Select Lvl,ID,Pt,Element,Attribute,Value,XPath,Seq From cte0
Union All
Select Lvl = p.Lvl+1
,ID = p.ID + Row_Number() over (Order By (Select NULL))
,Pt = p.ID
,Element = p.Element
,Attribute = x.value('local-name(.)','varchar(150)')
,Value = x.value('.','varchar(max)')
,XPath = p.XPath + '/#' + x.value('local-name(.)','varchar(max)')
,Seq = cast(concat(p.Seq,' ',10000000+p.ID + Row_Number() over (Order By (Select NULL)) ) as varchar(max))
From cte0 p
Cross Apply AttData.nodes('/*/#*') a(x)
) A
)
Select A.R1
,R2 = IsNull((Select max(R1) From cte1 Where Seq Like A.Seq+'%'),A.R1)
,A.Lvl
,A.ID
,A.Pt
,A.Element
,A.Attribute
,A.XPath
,Title = Replicate('|---',Lvl-1)+Element+IIF(Attribute='','','#'+Attribute)
,A.Value
From cte1 A
/*
Source: http://beyondrelational.com/modules/2/blogs/28/posts/10495/xquery-lab-58-select-from-xml.aspx
Declare #XML xml='<person><firstname preferred="Annie" nickname="BeBe">Annabelle</firstname><lastname>Smith</lastname></person>'
Select * from [dbo].[udf-XML-Hier](#XML) Order by R1
*/

Create multiple rows in table from existing rows?

With SQL, I have a table with key made of 1st three columns. All columns are small int values. There are a total of 21 columns per row.
I want to insert 80 new keys for every existing key. For example, first key is 1 201 0. I want to now update the table to also have keys 1 201 1, 1 201 2, 1 201 3, ... and keep the values present in the original row the same, duplicating the original row except for the new key structure.
I can do this with a program (read the table and then do the inserts in a loop), but I would like to know how to do this as a SQL statement.
If you are at least using SQL Server 2008 you can use the CROSS APPLY operator. This do the task:
DECLARE #T1 AS TABLE (ID INT)
DECLARE #T2 AS TABLE (ID1 INT, ID2 INT, ID3 INT)
INSERT INTO #T1 VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10),
(11), (12), (13), (14), (15), (16), (17), (18), (19), (20),
(21), (22), (23), (24), (25), (26), (27), (28), (29), (30),
(31), (32), (33), (34), (35), (36), (37), (38), (39), (40),
(41), (42), (43), (44), (45), (46), (47), (48), (49), (50),
(51), (52), (53), (54), (55), (56), (57), (58), (59), (60),
(61), (62), (63), (64), (65), (66), (67), (68), (69), (70),
(71), (72), (73), (74), (75), (76), (77), (78), (79), (80)
INSERT INTO #T2 VALUES (1, 201, 0)
INSERT INTO #T2
SELECT ID1, ID2, ID3 + T1.ID
FROM #T2 AS T2
CROSS APPLY (SELECT ID
FROM #T1) AS T1
Just replace "#T2" with your table and, of course, comment the insert in "#T2"
Hope this helps.
Cheers
Also, if you are using SQL Server 2008, you can potentially use ROW_NUMBER().
Insert Into [Table]
(
[Key1]
,[Key2]
,[Key3]
,[DataColumn1]
,[DataColumn2]
)
(
SELECT
[Key1] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int)
,[Key2] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int)
,[Key3] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int)
,[DataColumn1]
,[DataColumn2]
FROM [Table]
)
This will Insert all rows from Table ordering them by your 3 Key colums and add their row value to each of the individual Key columns. I don't know exactly what your data looks like, but this kind of query could create a collision on your 3 keys. You could possibly seed each ROW_NUMBER CAST with a value that is greater than the Max(Key). You just need to be creative with the Seed Value.
Insert Into [Table]
(
[Key1]
,[Key2]
,[Key3]
,[DataColumn1]
,[DataColumn2]
)
(
SELECT
[Key1] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int) + SeedValue
,[Key2] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int) + SeedValue
,[Key3] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int) + SeedValue
,[DataColumn1]
,[DataColumn2]
FROM [Table]
)
If you want to be more selective regarding the rows to copy, you can use a where clause in the second select statement:
Insert Into [Table]
(
[Key1]
,[Key2]
,[Key3]
,[DataColumn1]
,[DataColumn2]
)
(
SELECT
[Key1] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int) + SeedValue
,[Key2] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int) + SeedValue
,[Key3] + CAST( ROW_NUMBER() OVER (ORDER BY [Key1], [Key2], [Key3]) as int) + SeedValue
,[DataColumn1]
,[DataColumn2]
FROM [Table] Where Key1=Something and Key2=Something
)

SQL Server hangs

I'm training on SQL Server 2012 and I had no problem till today. It suddenly started hanging when trying to create new database, backup a database or basically almost any option that involves databases. If I switch instance everything works fine. When I choose the create database option for example it just loads for about 3-4mins then stops loading like nothing happened and brings up the "new database" window 5mins later. I tried tracking the queries running with server profiler but they don't make any sense really. The only process I managed to find that took 218 secs was the one in this picture. I've also attached the code of that query if it makes any sense.
exec sp_executesql N'
create table #tempbackup (database_name nvarchar(128), [type] char(1), backup_finish_date datetime)
insert into #tempbackup select database_name, [type], max(backup_finish_date) from msdb..backupset where [type] = ''D'' or [type] = ''L'' or [type]=''I'' group by database_name, [type]
create table #tmp_sp_db_vardecimal_storage_format (dbname sysname null, vardecimal_enabled varchar(3) null)
if exists (select o.object_id from sys.system_objects o where o.name=N''sp_db_vardecimal_storage_format'')
begin
insert into #tmp_sp_db_vardecimal_storage_format exec sys.sp_db_vardecimal_storage_format
end
DECLARE #is_policy_automation_enabled bit
SET #is_policy_automation_enabled = (SELECT CONVERT(bit, current_value)
FROM msdb.dbo.syspolicy_configuration
WHERE name = ''Enabled'')
create table #tmp_db_hadr_dbrs (group_database_id uniqueidentifier, synchronization_state tinyint, is_local bit)
declare #HasViewPermission int
select #HasViewPermission = HAS_PERMS_BY_NAME(null, null, ''VIEW SERVER STATE'')
if (#HasViewPermission = 1)
begin
insert into #tmp_db_hadr_dbrs select group_database_id, synchronization_state, is_local from master.sys.dm_hadr_database_replica_states
end
SELECT
dtb.name AS [Name],
(select count(*) from master.dbo.sysprocesses p where dtb.database_id=p.dbid) AS [ActiveConnections],
dtb.is_auto_close_on AS [AutoClose],
dtb.is_auto_shrink_on AS [AutoShrink],
dtb.compatibility_level AS [CompatibilityLevel],
dtb.create_date AS [CreateDate],
CAST(0 AS float) AS [DataSpaceUsage],
CAST(0 AS bit) AS [DboLogin],
N'''' AS [DefaultFileGroup],
'''' AS [DefaultSchema],
dtb.database_id AS [ID],
CAST(0 AS float) AS [IndexSpaceUsage],
CAST(has_dbaccess(dtb.name) AS bit) AS [IsAccessible],
CAST(0 AS bit) AS [IsDbAccessAdmin],
CAST(0 AS bit) AS [IsDbBackupOperator],
CAST(0 AS bit) AS [IsDbDatareader],
CAST(0 AS bit) AS [IsDbDatawriter],
CAST(0 AS bit) AS [IsDbDdlAdmin],
CAST(0 AS bit) AS [IsDbDenyDatareader],
CAST(0 AS bit) AS [IsDbDenyDatawriter],
CAST(0 AS bit) AS [IsDbOwner],
CAST(0 AS bit) AS [IsDbSecurityAdmin],
dtb.is_fulltext_enabled AS [IsFullTextEnabled],
CAST(case when dtb.name in (''master'',''model'',''msdb'',''tempdb'') then 1 else dtb.is_distributor end AS bit) AS [IsSystemObject],
suser_sname(dtb.owner_sid) AS [Owner],
ISNULL(df.physical_name, N'''') AS [PrimaryFilePath],
(dtb.is_published*1+dtb.is_subscribed*2+dtb.is_merge_published*4) AS [ReplicationOptions],
CAST(0 AS float) AS [Size],
CAST(0 AS float) AS [SpaceAvailable],
case
when dtb.collation_name is null then 0x200
else 0
end |
case
when 1 = dtb.is_in_standby then 0x40
else 0
end |
case dtb.state
when 1 then 0x2
when 2 then 0x8
when 3 then 0x4
when 4 then 0x10
when 5 then 0x100
when 6 then 0x20
else 1
end
AS [Status],
'''' AS [UserName],
dtb.is_ansi_null_default_on AS [AnsiNullDefault],
dtb.is_ansi_nulls_on AS [AnsiNullsEnabled],
dtb.is_ansi_padding_on AS [AnsiPaddingEnabled],
dtb.is_ansi_warnings_on AS [AnsiWarningsEnabled],
dtb.is_arithabort_on AS [ArithmeticAbortEnabled],
dtb.is_auto_create_stats_on AS [AutoCreateStatisticsEnabled],
dtb.is_auto_update_stats_on AS [AutoUpdateStatisticsEnabled],
CAST(CHARINDEX(N''_CS_'', dtb.collation_name) AS bit) AS [CaseSensitive],
dtb.is_cursor_close_on_commit_on AS [CloseCursorsOnCommitEnabled],
dtb.collation_name AS [Collation],
dtb.is_concat_null_yields_null_on AS [ConcatenateNullYieldsNull],
dtb.is_db_chaining_on AS [DatabaseOwnershipChaining],
CAST(( case LOWER(convert( nvarchar(128), DATABASEPROPERTYEX(dtb.name, ''Updateability''))) when ''read_write'' then 1 else 0 end) AS bit) AS [IsUpdateable],
(select backup_finish_date from #tempbackup where type = #_msparam_0 and db_id(database_name) = dtb.database_id) AS [LastBackupDate],
(select backup_finish_date from #tempbackup where type = #_msparam_1 and db_id(database_name) = dtb.database_id) AS [LastDifferentialBackupDate],
(select backup_finish_date from #tempbackup where type = #_msparam_2 and db_id(database_name) = dtb.database_id) AS [LastLogBackupDate],
dtb.is_local_cursor_default AS [LocalCursorsDefault],
dtb.is_numeric_roundabort_on AS [NumericRoundAbortEnabled],
dtb.page_verify_option AS [PageVerify],
dtb.is_quoted_identifier_on AS [QuotedIdentifiersEnabled],
dtb.is_read_only AS [ReadOnly],
dtb.recovery_model AS [RecoveryModel],
dtb.is_recursive_triggers_on AS [RecursiveTriggersEnabled],
dtb.user_access AS [UserAccess],
CAST(DATABASEPROPERTYEX(dtb.name, ''Version'') AS int) AS [Version],
dtb.is_auto_update_stats_async_on AS [AutoUpdateStatisticsAsync],
dtb.is_broker_enabled AS [BrokerEnabled],
drs.database_guid AS [DatabaseGuid],
ISNULL(DB_NAME(dtb.source_database_id), N'''') AS [DatabaseSnapshotBaseName],
dtb.is_date_correlation_on AS [DateCorrelationOptimization],
ISNULL((select top 1 ftc.name from sys.fulltext_catalogs as ftc where ftc.is_default=1),N'''') AS [DefaultFullTextCatalog],
CAST((case when drs.last_log_backup_lsn is not null then 1 else 0 end) AS bit) AS [HasFullBackup],
CAST(isnull(dtb.source_database_id, 0) AS bit) AS [IsDatabaseSnapshot],
CAST((select count(1) from sys.databases dtbmir where dtbmir.source_database_id = dtb.database_id) AS bit) AS [IsDatabaseSnapshotBase],
0 AS [IsMailHost],
CAST(case when dmi.mirroring_partner_name is null then 0 else 1 end AS bit) AS [IsMirroringEnabled],
dtb.is_parameterization_forced AS [IsParameterizationForced],
dtb.is_read_committed_snapshot_on AS [IsReadCommittedSnapshotOn],
case
when vardec.vardecimal_enabled = ''ON'' then cast(1 as bit)
else cast(0 as bit)
end
AS [IsVarDecimalStorageFormatEnabled],
ISNULL(dtb.log_reuse_wait,0) AS [LogReuseWaitStatus],
ISNULL(dmi.mirroring_failover_lsn,0) AS [MirroringFailoverLogSequenceNumber],
ISNULL(dmi.mirroring_guid,''00000000-0000-0000-0000-0000000000000000'') AS [MirroringID],
ISNULL(dmi.mirroring_partner_name,'''') AS [MirroringPartner],
ISNULL(dmi.mirroring_partner_instance,'''') AS [MirroringPartnerInstance],
ISNULL((case dmi.mirroring_redo_queue_type when N''UNLIMITED'' then 0 else dmi.mirroring_redo_queue end),0) AS [MirroringRedoQueueMaxSize],
ISNULL(dmi.mirroring_role,0) AS [MirroringRole],
ISNULL(dmi.mirroring_role_sequence,0) AS [MirroringRoleSequence],
ISNULL(dmi.mirroring_safety_level + 1, 0) AS [MirroringSafetyLevel],
ISNULL(dmi.mirroring_safety_sequence,0) AS [MirroringSafetySequence],
ISNULL(dmi.mirroring_state + 1, 0) AS [MirroringStatus],
ISNULL(dmi.mirroring_connection_timeout,0) AS [MirroringTimeout],
ISNULL(dmi.mirroring_witness_name,'''') AS [MirroringWitness],
ISNULL(dmi.mirroring_witness_state + 1, 0) AS [MirroringWitnessStatus],
drs.recovery_fork_guid AS [RecoveryForkGuid],
dtb.service_broker_guid AS [ServiceBrokerGuid],
dtb.snapshot_isolation_state AS [SnapshotIsolationState],
dtb.is_trustworthy_on AS [Trustworthy],
CAST(ISNULL(ctb.is_auto_cleanup_on,0) AS bit) AS [ChangeTrackingAutoCleanUp],
CAST(case when ctb.database_id is null then 0 else 1 end AS bit) AS [ChangeTrackingEnabled],
ISNULL(ctb.retention_period,0) AS [ChangeTrackingRetentionPeriod],
CAST(ISNULL(ctb.retention_period_units,0) AS tinyint) AS [ChangeTrackingRetentionPeriodUnits],
N'''' AS [DefaultFileStreamFileGroup],
CAST(dtb.is_encrypted AS bit) AS [EncryptionEnabled],
CAST(ISNULL(dek.database_id, 0) AS bit) AS [HasDatabaseEncryptionKey],
CAST(dtb.is_honor_broker_priority_on AS bit) AS [HonorBrokerPriority],
CAST(0 AS bit) AS [IsManagementDataWarehouse],
case when 1=#is_policy_automation_enabled and exists (select * from msdb.dbo.syspolicy_system_health_state where target_query_expression_with_id like ''Server''+ ''/Database\[#ID='' + convert(nvarchar(20),dtb.database_id) + ''\]%'' ESCAPE ''\'') then 1 else 0 end AS [PolicyHealthState],
dbrs.synchronization_state AS [AvailabilityDatabaseSynchronizationState],
dtb.containment AS [ContainmentType],
dtb.default_fulltext_language_lcid AS [DefaultFullTextLanguageLcid],
ISNULL(dtb.default_fulltext_language_name,N'''') AS [DefaultFullTextLanguageName],
dtb.default_language_lcid AS [DefaultLanguageLcid],
dtb.default_language_name AS [DefaultLanguageName],
ISNULL(fsopt.directory_name , N'''') AS [FilestreamDirectoryName],
ISNULL(fsopt.non_transacted_access , 0) AS [FilestreamNonTransactedAccess],
CAST(dtb.is_nested_triggers_on AS bit) AS [NestedTriggersEnabled],
dtb.target_recovery_time_in_seconds AS [TargetRecoveryTime],
CAST(dtb.is_transform_noise_words_on AS bit) AS [TransformNoiseWords],
dtb.two_digit_year_cutoff AS [TwoDigitYearCutoff],
dtb.name AS [DatabaseName],
dtb.name AS [DatabaseName2],
dtb.containment AS [ContainmentType2]
FROM
master.sys.databases AS dtb
LEFT OUTER JOIN sys.master_files AS df ON df.database_id = dtb.database_id and 1=df.data_space_id and 1 = df.file_id
LEFT OUTER JOIN sys.database_recovery_status AS drs ON drs.database_id = dtb.database_id
LEFT OUTER JOIN sys.database_mirroring AS dmi ON dmi.database_id = dtb.database_id
LEFT OUTER JOIN #tmp_sp_db_vardecimal_storage_format as vardec ON dtb.database_id = db_id(vardec.dbname)
LEFT OUTER JOIN sys.change_tracking_databases AS ctb ON ctb.database_id = dtb.database_id
LEFT OUTER JOIN sys.dm_database_encryption_keys AS dek ON dek.database_id = dtb.database_id
LEFT OUTER JOIN #tmp_db_hadr_dbrs AS dbrs ON dtb.group_database_id = dbrs.group_database_id and dbrs.is_local = 1
LEFT OUTER JOIN sys.database_filestream_options AS fsopt ON fsopt.database_id = dtb.database_id
WHERE
(dtb.name=#_msparam_3)
drop table #tempbackup
drop table #tmp_sp_db_vardecimal_storage_format
drop table #tmp_db_hadr_dbrs
',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000),#_msparam_2 nvarchar(4000),#_msparam_3 nvarchar(4000)',#_msparam_0=N'D',#_msparam_1=N'I',#_msparam_2=N'L',#_msparam_3=N'model'

Resources