Quantcast
Channel: Transact-SQL forum
Viewing all 23857 articles
Browse latest View live

Cannot drop database because it is currently in use

$
0
0

Dear colleagues,

I use SQL Server 2012. The exact version info is:

Microsoft SQL Server 2012 - 11.0.2100.60 (X64)   Feb 10 2012 19:39:15   Copyright (c) Microsoft Corporation  Standard Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor) 

I am flabbergasted. I try to drop a database, but that won't work because it says it is in use. But it isn't. I think I should no what to do, but actually I don't. Below, the SQL I use. Per statement, in the comment below, you can see the result. I cancelled the 'SET SINGLE_USER WITH ROLLBACK IMMEDIATE' after 4 minutes because nothing happened. This probably points to the real problem, but I cannot think what it is.

Kind Regards,

Chris Sijtsma

USE [master]
GO

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'Start10_64892_DB';
-- Commands completed successfully.
-- Completion time: 2020-04-15T07:09:32.7893007+02:00
GO

DROP DATABASE [Start10_64892_DB];
-- Msg 3702, Level 16, State 4, Line 9
-- Cannot drop database "Start10_64892_DB" because it is currently in use.
-- Completion time: 2020-04-15T07:10:10.1496410+02:00
GO

SELECT COUNT(1) FROM master.sys.sysprocesses p WHERE p.dbid = DB_ID(N'Start10_64892_DB');
-- Returns the value 0
GO

ALTER DATABASE [Start10_64892_DB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
--      :
-- Nonqualified transactions are being rolled back. Estimated rollback completion: 0%.
-- Nonqualified transactions are being rolled back. Estimated rollback completion: 0%.
-- Msg 5069, Level 16, State 1, Line 10
-- ALTER DATABASE statement failed.
-- Query was canceled by user.
GO


I want to increase the performance of a SQL view which have multiple joins and case statements

$
0
0

In my view I have multiple joins and one of the join is on many to many relation. So when I join this table the number of records increases drastically and to resolve it i have used case statement which helps in filtering the unwanted records. But this whole filtering of unwanted records is creating the query very slow.

Here is the basic structure of my query.

WITH PeriodCTE   AS (     SELECT PeriodId,            StartTime,          Name,
           LEAD(StartTime, 1) OVER (ORDER BY TimePeriodId) [EndTime]   FROM
 Period WHERE Active = 1 )
 Select * From (Select 
         Id, 
         Name, 
         Period,
         CASE      WHEN CAST(B.OpenTimestamp AS TIME) BETWEEN '00:00:00.0000000'           
                            AND (SELECT MIN(P.Starttime) FROM Period P 
                            INNER JOIN DepartmentPeriod DP ON P.PeriodId = DP.PeriodId 
                            WHERE DepartmentId = B.DepartmentId) 
                               AND CTE.StartTime = (SELECT MAX(T.Starttime) FROM 
                                                      Period P 
                                                    INNER JOIN 
                                                      DepartmentPeriod DP ON 
                                                      P.PeriodId = DP.PeriodId 
                                                    WHERE DepartmentId = B.DepartmentId) 
                   Then 1
                   When CAST(B.OpenTimestamp AS TIME) BETWEEN CTE.StartTime 
                       AND '23:59:59.9999999' AND CTE.StartTime = 
                            (SELECT MAX(P.Starttime) FROM Period P 
                                 INNER JOIN DepartmentPeriod DP ON 
                                P.TimePeriodId = DP.TimePeriodId 
                            WHERE DepartmentId = C.DepartmentId) 
                   Then 1
                   WHEN CAST(B.OpenTimestamp AS TIME) BETWEEN CTE.StartTime AND CTE.EndTime 
                   THEN 1
                   WHEN DP.DepartmentId NOT IN (SELECT DISTINCT(DepartmentId) FROM DepartmentPeriod) 
                   THEN 1
                   WHEN CTE.StartTime IS NULL
                   THEN 1          
          END AS [Flag] 
          From Bill AS B 
          LEFT OUTER JOIN Department AS D ON B.DepartmentId = D.DepartmentId 
          LEFT OUTER JOIN DepartmentPeriod AS DP ON D.DepartmentId = D.DepartmentId 
          LEFT OUTER JOIN PeriodCTE AS CTE ON P.PeriodId = DP.PeriodId ) AS X 
 Where Flag = 1

Are there any suggestions to improve the performance of my query.

Insert/Update XML file in SQL column

$
0
0

Hi, I have a table which has multiple Columns say FName, LName, City, XMLFile

FName is type varchar(20), LName is type varchar (20), City is type varchar(20)

XMLFile is of type XML.

Is there a easier way to insert or update the complete XML file  in SQL column ?

Please advise


Reason101

Same column name repeat twice during generate dynamic column name

$
0
0

see the code

	SELECT @columns =  
	COALESCE(@columns + ', ','') + QUOTENAME([Name])  
	FROM  
	   (  
	 SELECT e.ID, ISNULL(Period,'') [Name]        
	 From tblCalenderMaster AS d INNER JOIN        
	 tblCalenderDetail AS e ON d.ID = e.MasterID        
	 Where e.IsDeleted!='Y' AND d.TickerID=TickerID AND e.Period IN (SELECT TOP 100 PERCENT [Data] FROM dbo.SplitStringToTable(@Periods,',') ORDER BY ID)     
	 Group By e.ID, Period   
	   ) AS B  
	ORDER BY B.Name 

this line return SELECT TOP 100 PERCENT [Data] FROM dbo.SplitStringToTable(@Periods,',') ORDER BY ID

1Q 2020 and when i print @columns then saw it has same column name twice like [1Q 2020],[1Q 2020]

what to fix in the above code ?

thanks

Why STUFF function used in dynamic pivot

$
0
0

i know stuff replace character from start and end position but why it is used in dynamic pivot? please discuss with example. thanks

 SET @sql = N'        
 Select Ticker,Section,LineItem,XFundCode,OrderID ,'+STUFF(@columns,1,0,'')+'        
 From (        
  SELECT b.Ticker, b.Section, c.LineItem,XFundCode,OrderID,bg.[Values] Val, e.Period [Name]        
  FROM tblTicker_Bogey AS bg INNER JOIN        
   tblSectionLineItemTemplate AS a ON bg.SectionID=a.SectionID AND bg.LineItemID=a.LineItemID INNER JOIN         
   tblSectionTemplate AS b ON a.SectionID = b.SectionID INNER JOIN        
   TblLineItemTemplate AS c ON a.LineItemID = c.ID INNER JOIN        
   tblCalenderMaster AS d ON b.Ticker = d.TickerID INNER JOIN        
   tblCalenderDetail AS e ON d.ID = e.MasterID        
  WHERE (bg.[Values] IS NOT NULL) AND  (a.Active = ''A'') AND (e.IsDeleted <> ''Y'') AND b.Ticker='''+@TickerID+''' AND bg.PeriodID=e.ID        
   AND bg.MasterID=d.ID        
 )X PIVOT (MAX(Val) FOR [Name] IN ('+STUFF(@columns,1,0,'')+')) AS p        
 ORDER BY OrderID       
 ' 

In dynamic pivot how to order dynamic column by ID

$
0
0

here i create a sample scenario where i need to order dynamic column by orderid see the code.

create table #temp
(
    OrderID int,
    category varchar(3),
    amount money
)

insert into #temp values (1, 'ABC', 1000.00)
insert into #temp values (2, 'DEF', 500.00)
insert into #temp values (3, 'GHI', 800.00)
insert into #temp values (2, 'DEF', 700.00)
insert into #temp values (1, 'ABC', 1100.00)

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end

set @query = 
'SELECT * from 
(
    select  OrderID,amount, category from #temp
) src
pivot 
(
    max(amount) for category in (' + @cols + ')
) piv ORDER BY OrderID'

execute(@query)
drop table #temp
the moment i include orderid in dynamic pivot then many values is coming NULL. how to fix this scenario with dynamic column order. thanks

Update query

$
0
0

I would like to update all the columns in my table to remove the speech marks from the fields.

the below script will update on field

UPDATE tbtest
SET [column 1] = REPLACE([column 1], '"', '')

I've written the below script to out all possible updates available from the columns, but I'm stuck on the last bit of the REPLACE script.  any help on this.

SELECT 'UPDATE tbtest SET ' + COLUMN_NAME + ' = REPLACE(' + COLUMN_NAME + ''
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tbtest '
AND IS_NULLABLE = 'YES' AND DATA_TYPE IN ('char', 'nchar', 'varchar', 'nvarchar')

Generic "delete trigger" which creates a record in an audit-table

$
0
0

All

I have a database with several tables.

On some of those tables I want do to an audit: if a record is deleted, an entry should be created in table tblAudit.

tblAudit contains some fields: 
table: the table in which the record was deleted
On: the date on which the record was deleted
Value: a concatination of all fields of the related record

So let's assume I have a table tblA with next fields: Date, ProductName, Price
If I delete a record, field [Value] in my audit table should contain the actual values of the record I deleted together with the fieldname:  Date = 15/3/2019 €€€€€ ProductName = Bike €€€€€ price = 20.50

I also have table tblB with next fields: Supplier, Address, City, email
If I delete a record in this table, field [Value] in my audit table should contain:
Supplier = "The Online Bookstore" €€€€€ Address = "High End Street 20" €€€€€ City = "Washington" €€€€€ email="info@bookstore.com"

By the way: the €-signs are in to have the fields delimited later on.

Now, I could create individual triggers on each tables and each trigger contains a concatination of all those fieds.
I do not want to do this. I want some query which picks up each of the fieldnames and the field values dynamically regardless of the amount of fields the table has.  So with other words: I have one generic trigger which can be applied to any table.


Reparented Hierarchy tree to generate next sequential HID

$
0
0

I want to work out to create next hierarchy sequence id when reparenting hierarchy tree

i.e.

HID tree /3/, /3/1/, /3/2/, /3/2/1/, /3/2/2/, /3/2/3/

Reparenting /3/2/.... tree to /5/ will remain /5/2/ and it's subsequent series.

Is there any way when we can start /5/1/ if there is no child and if any child get next HID i.e /5/2/ and so on.

Thanks


DA

Calculate the Age with current date

$
0
0

Hi - I have to calculate the age of the following DOB with current date and want to get the result (YY  MM  DD   Week   Hrs)

DOB - 01/01/1956 

Current Date: 15/04/2020

/*Result of the following column*/

YY    MM    DD   Week     Hrs

converting from Derby to SQL Server- create trigger issue

$
0
0

Hi all,

thanks for your time

new to Ms SQL server

trying to convert derby based sqls in to mssql 


converted MsSQL query

CREATE TRIGGER CSS_SI_FILE_HIST_TRG ON CSS_SI_FILES
AFTER UPDATE OF REVISION
 OLD_TABLE AS updated_files
            NEW_TABLE AS deleted_files

sg 156, Level 15, State 1, Procedure CSS_SI_FILE_HIST_TRG, Line 7 [Batch Start Line 317]

Incorrect syntax near the keyword 'OF'.

---------------------------

Original derby trigger 

CREATE TRIGGER CSS_SI_FILE_HIST_TRG
AFTER UPDATE OF REVISION ON CSS_SI_FILES
REFERENCING OLD_TABLE AS updated_files
            NEW_TABLE AS deleted_files
FOR EACH STATEMENT
   INSERT INTO CSS_SI_FILE_HIST(SERVICE_INSTANCE_ID, FILE_ID, ITEM_TYPE, NAME, NAMESPACE, REVISION, REVISION_TIME, TXN_ID, PARENT_ID,
                                LOOKUP_KEY, FULL_PATH, PATH_DEPTH,
                                CONTENT_ID, CONTENT_EXT_ID, CONTENT_UUID, CONTENT_LENGTH, CONTENT_TYPE, CONTENT_CHARSET, CONTENT_MODIFIED_TIME,
                                TARGET_PATH, RENAMED_FROM_PATH,
                                ACL_ID, OBJ_TYPE, OBJ_TYPE_VER,
                                OWNED_BY_NAME, OWNED_BY_TYPE, SYS_CREATED_BY_NAME, SYS_CREATED_BY_TYPE, SYS_MODIFIED_BY_NAME, SYS_MODIFIED_BY_TYPE,
                                SYS_CREATED_TIME, SYS_MODIFIED_TIME, 
                                CREATED_BY_NAME, CREATED_BY_TYPE, MODIFIED_BY_NAME, MODIFIED_BY_TYPE,
                                CREATED_TIME, MODIFIED_TIME, CUST_FLAGS,
                                EXT_ATTRIBUTES, IS_DELETED)
      SELECT SERVICE_INSTANCE_ID, FILE_ID, ITEM_TYPE, NAME, NAMESPACE, REVISION, REVISION_TIME, TXN_ID, PARENT_ID,
             LOOKUP_KEY, FULL_PATH, PATH_DEPTH,
             CONTENT_ID, CONTENT_EXT_ID, CONTENT_UUID, CONTENT_LENGTH, CONTENT_TYPE, CONTENT_CHARSET, CONTENT_MODIFIED_TIME,
             TARGET_PATH, RENAMED_FROM_PATH,
             ACL_ID, OBJ_TYPE, OBJ_TYPE_VER,
             OWNED_BY_NAME, OWNED_BY_TYPE, SYS_CREATED_BY_NAME, SYS_CREATED_BY_TYPE, SYS_MODIFIED_BY_NAME, SYS_MODIFIED_BY_TYPE,
             SYS_CREATED_TIME, SYS_MODIFIED_TIME, 
             CREATED_BY_NAME, CREATED_BY_TYPE, MODIFIED_BY_NAME, MODIFIED_BY_TYPE,
             CREATED_TIME, MODIFIED_TIME, CUST_FLAGS,
             EXT_ATTRIBUTES, IS_DELETED
        FROM updated_files
      UNION ALL
      SELECT SERVICE_INSTANCE_ID, FILE_ID, ITEM_TYPE, NAME, NAMESPACE, REVISION, REVISION_TIME, TXN_ID, PARENT_ID,
             LOOKUP_KEY, FULL_PATH, PATH_DEPTH,
             CAST(NULL AS BIGINT), CAST(NULL AS VARCHAR(255)), CAST(NULL AS CHAR(16) FOR BIT DATA), 
             CAST(NULL AS BIGINT), CAST(NULL AS VARCHAR(255)), CAST(NULL AS VARCHAR(255)), CAST(NULL AS TIMESTAMP),
             TARGET_PATH, RENAMED_FROM_PATH,
             CAST(NULL AS BIGINT), OBJ_TYPE, OBJ_TYPE_VER,
             OWNED_BY_NAME, OWNED_BY_TYPE, SYS_CREATED_BY_NAME, SYS_CREATED_BY_TYPE, SYS_MODIFIED_BY_NAME, SYS_MODIFIED_BY_TYPE,
             SYS_CREATED_TIME, SYS_MODIFIED_TIME, 
             CREATED_BY_NAME, CREATED_BY_TYPE, MODIFIED_BY_NAME, MODIFIED_BY_TYPE,
             CREATED_TIME, MODIFIED_TIME, CUST_FLAGS,
             CAST(NULL AS CLOB), IS_DELETED
        FROM deleted_files 
       WHERE IS_DELETED = TRUE
;

Query uses 100% memory in LocalDB but runs fine in SQL Server Express

$
0
0

The following function is fine in SQL Server express but using LocalDB it crashes the computer:

After creating function - to calculate the score on a bridge hand given the board number, declarer, contract and result

select dbo.fn_CalculateBoardScore (1, 'N', '4 H', '=')

The Function:

CREATE FUNCTION [dbo].[fn_CalculateBoardScore] 
(
@BoardNo int,
@Declarer varchar(1),
@Contract varchar(10),
@result varchar(3)
)
RETURNS int

AS
BEGIN
DECLARE 
@Vul int = 0,
@IsPlayed varchar(1) = '1',
@NumTricksBid int,  /*Number of tricks Bid for*/
@Denomination varchar(1), /*Spade=S, Heart=H, Diamond=D, Club=C, NoTrump=N, PassedIn=P*/
@MajMinNt int,   /* minor=0, Major=1, NT=2*/
@Doubled int = 0,
@ReDoubled int = 0,
@TricksMade int = 0,
@UnderTricks int =0,
@ScoreValue int,
@DecVul int = 0,
@TrickScore int =0,
@SSlamBonus int = 500,
@GSlamBonus int = 1000,
@Overtricks int,
@OvertrickValueNV int,
@OvertrickValueVul int = 0,
@PartScoreBonus int = 50,
@GameScoreBonus int = 300,
@DoubledBonus int = 0,
@ReDoubledBonus int = 0,

@MinorTrickValue int = 20,
@MajorTrickValue int = 30,
@NotrumpFirstTrickValue int = 40,

@Under1NV int = -50,
@Under1Vul int = -100,
@Under2PlusNV int =-50,
@Under2PlusVul int = -100,
@Under4PlusNV int = 0,
@TrickCounter int =0
/*---------------------------------------*/
/*Find out who's vul on this board*/
set @Vul = (@BoardNo - 1 + ((@BoardNo-1)/4)%4)%4 

if((@Vul=1 OR @Vul=3) AND (@Declarer='N' OR @Declarer='S'))
Begin
set @DecVul=1
set @GameScoreBonus = 500
set @SSlamBonus = 750
set @GSlamBonus = 1500
 
END
if((@Vul=2 OR @Vul=3) AND (@Declarer='E' OR @Declarer='W'))
Begin
set @DecVul=1
set @GameScoreBonus = 500
set @SSlamBonus = 750
set @GSlamBonus = 1500
END

/*Clear out any spaces*/
set @contract=REPLACE ( @Contract, ' ' , ''  )
set @contract=UPPER ( @Contract )
set @contract=REPLACE ( @Contract, 'NT' , 'N'  )
/* Check if the board was actually played in a contract*/
set @IsPlayed=SUBSTRING(@contract,1,1)

SELECT @NumTricksBid = 
CASE @IsPlayed
when 'P' then 0
when '1' then 1
when '2' then 2
when '3' then 3
when '4' then 4
when '5' then 5
when '6' then 6
when '7' then 7
 
ELSE NULL
 
END

IF (@Contract='NP' OR @Contract is null)
BEGIN
set @ScoreValue = -9001
RETURN @ScoreValue
END

IF (@NumTricksBid is NULL)
BEGIN
set @ScoreValue = NULL
RETURN @ScoreValue
END
ELSE IF (@NumTricksBid = 0)
BEGIN
set @ScoreValue = 0
RETURN @ScoreValue
END

/* If passed in or Not Played then function should not reach here!!!!!*/

/* Now find the Denomination*/
set @Denomination=SUBSTRING(@contract,2,1)

/* And the number of tricks actually made in NZ terms e.g. 3H +2 is making 5*/
SELECT @TricksMade =
case @result
WHEN '=' then @NumTricksBid
WHEN '+1' then @NumTricksBid + 1
WHEN '+2' then @NumTricksBid + 2
WHEN '+3' then @NumTricksBid + 3
WHEN '+4' then @NumTricksBid + 4
WHEN '+5' then @NumTricksBid + 5
WHEN '+6' then @NumTricksBid + 6
ELSE 0
END

/* If failed contract - set Undertricks*/
SELECT @UnderTricks =
case @result
WHEN '-1' then 1
WHEN '-2' then 2
WHEN '-3' then 3
WHEN '-4' then 4
WHEN '-5' then 5
WHEN '-6' then 6
WHEN '-7' then 7
WHEN '-8' then 8
WHEN '-9' then 9
WHEN '-10' then 10
WHEN '-11' then 11
WHEN '-12' then 12
WHEN '-13' then 13
ELSE 0
END


/* Now find out if Major, Minor or NT contract*/
SELECT @MajMinNt =  
case @Denomination
WHEN 'C' then 0
WHEN 'D' then 0
WHEN 'H' then 1
WHEN 'S' then 1
WHEN 'N' then 2
ELSE NULL
END

/* Find out if it was doubled or re-doubled*/
IF (SUBSTRING(@contract,3,1)='X')
BEGIN
set @Doubled = 1
set @DoubledBonus = 50
set @MinorTrickValue = 40
set @MajorTrickValue = 60
set @NotrumpFirstTrickValue = 80
set @OvertrickValueNV = 100
set @OvertrickValueVul = 200

set@Under1NV  = -100
set@Under1Vul  = -200
set@Under2PlusNV  =-200
set@Under2PlusVul  = -300
set@Under4PlusNV  = -100



IF (SUBSTRING(@contract,4,1)='X')
BEGIN
set @ReDoubled = 1
set @ReDoubledBonus = 100
set @DoubledBonus = 0
set @MinorTrickValue = 80
set @MajorTrickValue = 120
set @NotrumpFirstTrickValue = 160
set @OvertrickValueNV = 200
set @OvertrickValueVul = 400

set@Under1NV  = -200
set@Under1Vul  = -400
set@Under2PlusNV  =-400
set@Under2PlusVul  = -600
set@Under4PlusNV  = -200

END
END

/* NOW we know what the contract is, if it was doubled or re-doubled, AND tricks made*/

IF (@MajMinNt=0 AND @TricksMade>0)
BEGIN
IF (@OvertrickValueNV=0) 
BEGIN
set @OvertrickValueNV=@MinorTrickValue
END
IF (@OvertrickValueVul=0) 
BEGIN
set @OvertrickValueVul=@MinorTrickValue
END

set @ScoreValue= @NumTricksBid * @MinorTrickValue
if (@ScoreValue < 100)
begin
set @ScoreValue= @TricksMade * @MinorTrickValue + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus
IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=0)
BEGIN
set @ScoreValue= @NumTricksBid * @MinorTrickValue + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueNV
END

IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=1)
BEGIN
set @ScoreValue= @NumTricksBid * @MinorTrickValue + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueVul
END


end
else if (@ScoreValue >= 100)

begin
set @ScoreValue= @TricksMade * @MinorTrickValue + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus
IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=0)
BEGIN
set @ScoreValue= @NumTricksBid * @MinorTrickValue + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueNV
END

IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=1)
BEGIN
set @ScoreValue= @NumTricksBid * @MinorTrickValue + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueVul
END
IF (@NumTricksBid=6)
BEGIN
set @ScoreValue=  @ScoreValue + @SSlamBonus
END
IF (@NumTricksBid=7)
BEGIN
set @ScoreValue=  @ScoreValue + @GSlamBonus
END
end

END

/*--=====================================================================*/
IF (@MajMinNt=1 AND @TricksMade>0)
BEGIN
IF (@OvertrickValueNV=0) 
BEGIN
set @OvertrickValueNV=@MajorTrickValue
END
IF (@OvertrickValueVul=0) 
BEGIN
set @OvertrickValueVul=@MajorTrickValue
END

set @ScoreValue= @NumTricksBid * @MajorTrickValue
if (@ScoreValue < 100)
begin
set @ScoreValue= @TricksMade * @MajorTrickValue + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus
IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=0)
BEGIN
set @ScoreValue= @NumTricksBid * @MajorTrickValue + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueNV
END

IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=1)
BEGIN
set @ScoreValue= @NumTricksBid * @MajorTrickValue + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueVul
END


end
else if (@ScoreValue >= 100)
/*begin*/
/*set @ScoreValue=@TricksMade * @MinorTrickValue + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus*/
/*end*/

begin
set @ScoreValue= @TricksMade * @MajorTrickValue + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus
IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=0)
BEGIN
set @ScoreValue= @NumTricksBid * @MajorTrickValue + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueNV
END

IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=1)
BEGIN
set @ScoreValue= @NumTricksBid * @MajorTrickValue + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueVul
END
IF (@NumTricksBid=6)
BEGIN
set @ScoreValue=  @ScoreValue + @SSlamBonus
END
IF (@NumTricksBid=7)
BEGIN
set @ScoreValue=  @ScoreValue + @GSlamBonus
END
end

END

/*--=====================================================================*/
IF (@MajMinNt=2 AND @TricksMade>0)
BEGIN
IF (@OvertrickValueNV=0) 
BEGIN
set @OvertrickValueNV=@MajorTrickValue
END
IF (@OvertrickValueVul=0) 
BEGIN
set @OvertrickValueVul=@MajorTrickValue
END

set @ScoreValue= @NumTricksBid * @MajorTrickValue +10
if (@ScoreValue < 100)
begin
set @ScoreValue= @TricksMade * @MajorTrickValue + 10 + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus
IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=0)
BEGIN
set @ScoreValue= @NumTricksBid * @MajorTrickValue + 20 + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueNV
END

IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=1)
BEGIN
set @ScoreValue= @NumTricksBid * @MajorTrickValue + 20 + @PartScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueVul
END


end
else if (@ScoreValue >= 100)

begin
set @ScoreValue= @TricksMade * @MajorTrickValue + 10 + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus
IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=0)
BEGIN
set @ScoreValue= @NotrumpFirstTrickValue + ((@NumTricksBid - 1) * @MajorTrickValue) + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueNV
END

IF ((@Doubled=1 OR @ReDoubled=1) AND @DecVul=1)
BEGIN
set @ScoreValue= @NotrumpFirstTrickValue + ((@NumTricksBid - 1) * @MajorTrickValue) + @GameScoreBonus + @DoubledBonus + @ReDoubledBonus + (@TricksMade-@NumTricksBid)*@OvertrickValueVul
END
IF (@NumTricksBid=6)
BEGIN
set @ScoreValue=  @ScoreValue + @SSlamBonus
END
IF (@NumTricksBid=7)
BEGIN
set @ScoreValue=  @ScoreValue + @GSlamBonus
END
end


END

/*-=====================================---*/
/*-                                     ---*/
/*-  NOW for the failing contracts!!!   ---*/
/*-                                     ---*/
/*-=====================================*/
IF (@UnderTricks>0)
BEGIN
IF(@DecVul=0)
BEGIN
set @ScoreValue = @Under1NV + (@UnderTricks-1)*@Under2PlusNV
IF(@UnderTricks>3)
BEGIN
set @ScoreValue = @ScoreValue + (@UnderTricks-3)*@Under4PlusNV
END

RETURN @ScoreValue

END
ELSE IF(@DecVul=1) 
BEGIN
set @ScoreValue = @Under1Vul + (@UnderTricks-1)*@Under2PlusVul

RETURN @ScoreValue

END
END
RETURN @ScoreValue

END
GO

moving the child rows at the parent level and keep parent

$
0
0

Hi there, my aim is just keep in the same row all the childs that belongs to a parent and keep the own parent's value.

DDL plus some data to test:

DECLARE @t TABLE(id INT PRIMARY KEY, val VARCHAR(MAX), categ varchar(200), additional varchar(200))

INSERT INTO @t VALUES
(1, '25002230602491', 'cocotte-ovale-sale', 'direct_heat1,induction_cooker,oven,dish_washer'),
(2, '25002230607611', 'cocotte-ovale-sale','direct_heat2,induction_cooker,oven,dish_washer'),
(3, '123123123', 'cocotte-ovale-sale','direct_heat3,induction_cooker,oven,dish_washer'),
(4, '9991', 'test',NULL),
(5, '9992', 'test',NULL),
(6, '9993', 'test',NULL),
(7, '9994', 'test',NULL),
(8, 'cocotte-ovale-sale',NULL, 'valueparent1,valueparent2,valueparent3,valueparent4'),
(9, 'test',NULL, 'valueparentTEST1,valueparentTEST2,valueparentTEST3,valueparentTEST4');

select * from @t;

WITH CTE AS
(SELECT row_number() OVER (PARTITION BY categ ORDER BY id ASC) rn_a
,row_number() OVER (PARTITION BY categ ORDER BY id DESC) rn_d,
id,
CAST(val AS VARCHAR(MAX)) val,
categ,
dbo.GetColumnValue(additional, ',', 1) as Product_Support_Devices1,
dbo.GetColumnValue(additional, ',', 2) as Product_Support_Devices2,
dbo.GetColumnValue(additional, ',', 3) as Product_Support_Devices3,
dbo.GetColumnValue(additional, ',', 4) as Product_Support_Devices4
FROM @t
),
CTE2 AS
(SELECT * FROM CTE WHERE rn_a = '1'
UNION ALL
SELECT CTE.rn_a, CTE.rn_d, CTE2.id, CAST(CONCAT(CTE2.val, ',', CTE.val) AS VARCHAR(MAX)), CTE2.categ, 
CTE.Product_Support_Devices1,
CTE.Product_Support_Devices2,
CTE.Product_Support_Devices3,
CTE.Product_Support_Devices4
FROM CTE JOIN CTE2 ON CTE.rn_a = CTE2.rn_a + 1 AND CTE.categ = CTE2.categ
)
SELECT * FROM CTE2 WHERE rn_d = '1'

current outcome is not desired, i am not having the values for the sku: "cocotte-ovale-sale" ("valueparent1,valueparent2,valueparent3,valueparent4") but the ones for a child

"direct_heat3,induction_cooker,oven,dish_washer"


expected outcome:

val: 25002230602491,25002230607611,123123123

categ: cocotte-ovale-sale

Product_Support_Devices1: valueparent1

Product_Support_Devices2: valueparent2

Product_Support_Devices3: valueparent3

Product_Support_Devices4: valueparent4

Thanks in advance for any input or hint on this,

Enric

How to dynamically set OUTPUT file name from sqlcmd

$
0
0

Hello,

I run this command from OS

sqlcmd -S sql-12 -I -i get_db_list.sql 

and I want dynamically to generate output filename, here is get_db_list.sql 

declare @instname varchar  = (SELECT @@servicename)
go

:OUT $(instname)
SELECT name FROM master.dbo.sysdatabases
go
:OUT stdout

but the script returned the error

'instname' scripting variable not defined.

and generated filename is "$(instname)"

How to put sql variable into env :OUT variable?

Thanks.

Marian

Difference in the DateDiff result

$
0
0

Hello, Why the output is same for both queries. The output should be difference because one query is subtracting -64 year and in other -64.5 (64 year and half year).

SELECT   DateADD(DD, 0 , DateADD(YEAR, -64, '2020-04-01'))  
SELECT   DateADD(DD, 0 , DateADD(YEAR, -64.5, '2020-04-01')) 

--Current output  for both query.
1956-04-01 00:00:00.000


is there a way to feed a VIEW the results of a Stored Proc?

$
0
0

is there a way to feed a view the results of a stored proc?  Can I execute a Stored Proc from within a view, and return the results of the Stored Proc in a View?

Microsoft SQL Server 2012 (SP1) - 11.0.3156.0 (X64)
    May  4 2015 18:48:09
    Copyright (c) Microsoft Corporation
    Standard Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )

GROUP BY DATE FIELD PROBLEM

$
0
0
I have an interesting GROUP BY on a DATE field problem.

Query #1
SELECT
      CONVERT(CHAR(6), [logDate], 112) AS YYYYMM
       ,COUNT([MemberID]) AS CountOfMembers

  FROM [OSRD].[dbo].[OLBLoginsNoQuicken]

  WHERE logdate between '12/1/2019' and '12/31/2019'

  GROUP BY CONVERT(CHAR(6), [logDate], 112)
  ORDER BY CONVERT(CHAR(6), [logDate], 112)

If I run the query #1 just for one month and group the DATE field by YYYYMM format (For example, 12/1/2019 - 12/31/2019',
I get the CountOfMembers for 201912 as 1,358,353

Results CountOfMembers
2019121358353

Query #2
SELECT
      CONVERT(CHAR(6), [logDate], 112) AS YYYYMM
      ,COUNT([MemberID]) AS CountOfMembers

  FROM [OSRD].[dbo].[OLBLoginsNoQuicken]

  WHERE logdate between '12/1/2019' and '03/31/2020'

  GROUP BY CONVERT(CHAR(6), [logDate], 112)
  ORDER BY CONVERT(CHAR(6), [logDate], 112)

Now, if I run the query #2 for more than one month and still group the DATE field by YYYYMM format (For example, 12/1/2019 - 3/31/2020',
I get the CountOfMembers for 201912 as 1,407,567 (totally different than when I run for just one month)

Results CountOfMembers
2019121407567
202001 1489026
202002 1475378
202003 1442368

I expect the number for 201912 to be the same.  Not quite understand why the numbers are different at this time.  I think I am not the right thing on the conversation of the DATE field to be YYYYMM.

Thank you,

How to split a single column value to multiple column value separted by comma

$
0
0

I have column it have multiple values with comma separated . Here is the sample table

Create table ##Temp (TypeName nvarchar(2000))
INSERT into ##Temp (Typename ) values
        ('100000002,100000004,100000012,200000000'),    
        ('100000002,100000009,200000000'),
('200000000,200000017'),
('200000000')
select * from ##Temp

looking out put something like this.

TypeName1   TypeName2      TypeName3     TypeName4
------------------------------------------------------------------

100000002     100000004        100000012        200000000
100000002     100000009        200000000
200000000     200000017
200000000

Appreciate your help .



Unique deadlock scenario with index rebuilds.

$
0
0

Greetings. I've got an existing Service Broker process that rebuilds indexes, specifically several at once using multi threading. Before it runs it gathers all indexes into a table, and removes those that don't meet certain criteria (number of pages, percent of fragmentation, etc). It works great, and has served us well for years. 

I now have a new project to move all objects into new database files, as we recently purged 1 TB of data and without doing this there's no way we'll ever be able to reclaim that space. Naturally, my thought was to use our SB process to make that magic happen w some slight tweaks. 

So first, a process runs that populates two tables with every index in the DB. 1) The existing table from the SB process. 2) A new table that holds similar data, but also has a "command" column that shows the exact line of rebuild code to be ran. Note that to move indexes to a new filegroup, one needs to run a CREATE INDEX ... WITH (DROP_EXISTING = ON) command. 

So here is a snippet of code that works without issue:

SET @SQL = 'USE ' + @dbname + ';
							IF EXISTS(SELECT 1 FROM SYS.Indexes WHERE name=''' + @idxname + ''' AND object_id = (select object_id from sys.objects where name = ''' + @tblName + ''' and schema_id = (select schema_id(''' + @schemaname + '''))))
								ALTER INDEX [' + @idxname + N'] ON [' + @schemaname + N'].[' + @tblname + N'] REBUILD WITH (Data_Compression=' + @compress + ', maxdop=0)
							ELSE
								UPDATE IndexMaint SET MaintMessage = ''INDEX NOT FOUND! SKIPPED'' WHERE IndexName = '''+ @idxname + ''' AND TableName = ''' + @tblName + ''''

Here is the only block of code that has changed. It works for the most part, but also causes some deadlocks (like 30 out of every 1000 indexes rebuild will deadlock):

						DECLARE @EXEC NVARCHAR(MAX)
							SET @EXEC = (SELECT commands 
							from perf.dbo.idx_relo_commands (nolock)
							where dbName = @dbName
							and schemaName = @schemaname
							and tableName = @tblName
							and indexName = @idxname)

							SET @SQL = 'USE ' + @dbname + ';
							IF EXISTS(SELECT 1 FROM SYS.Indexes WHERE name=''' + @idxname + ''' AND object_id = (select object_id from sys.objects where name = ''' + @tblName + ''' and schema_id = (select schema_id(''' + @schemaname + '''))))
													'+@exec+';
							IF NOT EXISTS(SELECT 1 FROM SYS.Indexes WHERE name=''' + @idxname + ''' AND object_id = (select object_id from sys.objects where name = ''' + @tblName + ''' and schema_id = (select schema_id(''' + @schemaname + '''))))
								UPDATE IndexMaint SET MaintMessage = ''INDEX NOT FOUND! SKIPPED'' WHERE IndexName = '''+ @idxname + ''' AND TableName = ''' + @tblName + ''''

Here is an output from Extended Events:

nametimestamptimestamp (UTC)wait_typeopcodedurationsignal_durationsession_idcallstackidprocess_utilizationsystem_idleuser_mode_timekernel_mode_timepage_faultsworking_set_deltamemory_utilizationcall_stacktypesourceos_errorsni_errorsni_consumer_errorsni_providerstatelocal_portremote_porttds_input_buffer_errortds_output_buffer_errortds_input_buffer_bytestds_flagstotal_login_time_mslogin_task_enqueued_msnetwork_writes_msnetwork_reads_msssl_processing_mssspi_processing_mslogin_trigger_and_resource_governor_processing_msconnection_idconnection_peer_idlocal_hostremote_hosterror_numberseverityuser_definedcategorydestinationis_interceptedmessagedatabase_idxml_reportcomponentdata
xml_deadlock_report2020-04-12 06:50:53.23738622020-04-12 13:50:53.2373862NULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULL<deadlock>   <victim-list>    <victimProcess id="process1de61db468"/>   </victim-list>   <process-list>   <process id="process1de61db468" taskpriority="0" logused="224" waitresource="OBJECT: 10:99023634:0 " waittime="19939" ownerId="29965710" transactionname="user_transaction" lasttranstarted="2020-04-12T09:50:00.900" XDES="0x29c46dd2f0" lockMode="Sch-M" schedulerid="2" kpid="9232" status="background" spid="38" sbid="0" ecid="0" priority="0" trancount="2">    <executionStack>      <frame procname="adhoc" line="3" stmtstart="514" stmtend="1174" sqlhandle="0x02000000c296b50d1da412e6dbef692b5c07d281e67135fa0000000000000000000000000000000000000000">  unknown    </frame>      <frame procname="mssqlsystemresource.sys.sp_executesql" line="1" stmtstart="-1" sqlhandle="0x0400ff7f427f99d9010000000000000000000000000000000000000000000000000000000000000000000000">  sp_executesql    </frame>      <frame procname="Perf.dbo.usp_ReIndex_internalActivationTarget_C2000" line="100" stmtstart="7746" stmtend="7820" sqlhandle="0x0300090093adc341f2b2a0009bab000001000000000000000000000000000000000000000000000000000000">  EXECUTE sp_executesql @SQL;    </frame>     </executionStack>     <inputbuf>     </inputbuf>    </process>    <process id="process1554671468" taskpriority="0" logused="624" waitresource="OBJECT: 10:1277676791:0 " waittime="7927" ownerId="29911258" transactionname="user_transaction" lasttranstarted="2020-04-12T09:48:55.027" XDES="0x144d0526a0" lockMode="Sch-M" schedulerid="15" kpid="12840" status="background" spid="75" sbid="0" ecid="0" priority="0" trancount="2">     <executionStack>     <frame procname="adhoc" line="3" stmtstart="506" stmtend="1168" sqlhandle="0x020000002998ac0a2c0d6940244a3fc970e0c2e81c3ff2310000000000000000000000000000000000000000">  unknown   </frame>      <frame procname="mssqlsystemresource.sys.sp_executesql" line="1" stmtstart="-1" sqlhandle="0x0400ff7f427f99d9010000000000000000000000000000000000000000000000000000000000000000000000">  sp_executesql    </frame>      <frame procname="Perf.dbo.usp_ReIndex_internalActivationTarget_C2000" line="100" stmtstart="7746" stmtend="7820" sqlhandle="0x0300090093adc341f2b2a0009bab000001000000000000000000000000000000000000000000000000000000">  EXECUTE sp_executesql @SQL;    </frame>     </executionStack>     <inputbuf>     </inputbuf>    </process>   </process-list>   <resource-list>   <objectlock lockPartition="0" objid="99023634" subresource="FULL" dbid="10" objectname="c2000.dbo.AdEnrollSched" id="lock2539272980" mode="Sch-M" associatedObjectId="99023634">    <owner-list>      <owner id="process1554671468" mode="Sch-M"/>     </owner-list>     <waiter-list>      <waiter id="process1de61db468" mode="Sch-M" requestType="wait"/>     </waiter-list>    </objectlock>    <objectlock lockPartition="0" objid="1277676791" subresource="FULL" dbid="10" objectname="c2000.dbo.AmCollegeTransfer" id="lock24bb079400" mode="Sch-M" associatedObjectId="1277676791">     <owner-list>      <owner id="process1de61db468" mode="Sch-M"/>    </owner-list>     <waiter-list>      <waiter id="process1554671468" mode="Sch-M" requestType="wait"/>     </waiter-list>    </objectlock>  </resource-list>  </deadlock>  NULLNULL

So my question (finally) is are this type of index rebuilds, called through Service Broker, simply prone to deadlocks? Everyone involved in this deadlock are trying to get locks for schema mods -- not like they're trying to read data. 

Thoughts?



Thanks in advance! ChrisRDBA

Time out error while creating Index

$
0
0

Getting timeout error while creating a index which uses partition schema. Tried changing the transaction time out value for table designer in SSMS but it did not work .

CREATE CLUSTERED INDEX IX_Indexname ON  dbo.order ([MONTH ID])
WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
  ON Month_PS([MONTH ID])

Viewing all 23857 articles
Browse latest View live