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

Joining Multiple Tables, one of them is a Pivot table

$
0
0

Hello -

I am using SQL Server 2012 std. ed. I primarily searched in this forum and googled it as well but I did not find the solution..hence I am here hoping some one will give me their time and effort helping out.

First query:

SELECT INV_ID,INVOICE_DATE, SUM(convert(float,AMOUNT)) AS 'Usage Charges'
FROM TBC_PaetecUsageImportTwo
GROUP BY INV_ID, INVOICE_DATE

Second query:

SELECT INV_ID,INVOICE_DATE, [Non-recurring Charges],[Recurring Charges],[Tax Charges]
FROM
(SELECT p.INV_ID,p.INVOICE_DATE, p.CMSN_DESC,AMOUNT
FROM TBC_PaetecNonUsageImport p
INNER JOIN TBC_CostByType c
ON p.TRANS_TYP_NM = c.TRANS_TYP_NM
WHERE c.Payee = 'TBC'
) ps
PIVOT
(
SUM(Amount)
        FOR [CMSN_DESC] IN ([Recurring Charges],[Tax Charges],[Non-recurring Charges])
        )
AS PivotTable

I'd like to join this two queries so I get the following fields:

INV_ID,INVOICE_DATE, [Usage Charges] -- from first query and,

[Non-recurring Charges],[Recurring Charges],[Tax Charges] from Second Query.

Please note that INV_ID,INVOICE_DATE from first query = INV_ID,INVOICE_DATE fromsecond query.

Is it possible? Thank you in advance!!


Sanjeev Jha


UPDATE TABLE using ROW_NUMBER() OVER...

$
0
0

Hi Champs,

I am trying to either UPDATE or add a new column with ROWNUMBER() OVER an column on a table

table:
ID------Col2----Col3---
1-------12---------1
1-------34---------2
2-------44---------1
2-------75---------2
2-------77---------3
3-------23---------1
3-------33---------2
4-------44---------1
4-------22---------2

I know I can get Col3 right with an SELECT and ROWNUMBER() OVER, but how can I UPDATE  the table with the result?

 

 

/Many thanks

 

TSQL verify sort order / UNION ALL

$
0
0
CREATE PROCEDURE Test
AS
BEGIN
SELECT * FROM (
SELECT 1 AS a,'test1' as b, 'query1' as c
UNION ALL
SELECT 2 AS a,'test22' as b, 'query22' as c
UNION ALL
SELECT 2 AS a,'test2' as b, 'query2' as c
UNION ALL
SELECT 3 AS a,'test3' as b, 'query3' as c
UNION ALL
SELECT 4 AS a,'test4' as b, 'query4' as c
) As sample
FOR XML RAW

END
  1. Can we guarantee that the stored procedure returns results in given order?

  2. Normally it says when we insert these select query to temporary table we can't guarantee its inserting order. So we have to use order by clause. But most of time it gives same order. Can we enforce to give it some different order? Is this related with clustered and non clustered indices.

  3. In second case can we enforce inserting order by adding Identity column?

Explain more on behind logic as well. I'm checking whether I need to add ORDER BY in old Stored Procedures or not.

Is my dynamic SQL vulnerable to SQL injection?

$
0
0

I'm concerned whether the routine I just write is vulnerable to SQL injection.

The final version will be an SP or UDF that accepts a multi-column CSV file passed in as one long string, to be converted into a temp table. (I'm doing this in case it proves useful on some older editions of SS).  I use Alter Table statements to create the columns based on the first row of source data. Example
    ALTER TABLE #table_CSV ADD 'column-name-goes-here' nvarchar(4000)
Could the client put some harmful malicious code on the first row of source data, instead of column names?

Then I do INSERT statements - here again, each of the column names is a string from the client. Is that dangerous? Likewise each of the values in the VALUES clause is a string from client. Is that dangerous? I could probably parameterize the INSERT but I was hoping to save a little coding work, if there's no real danger here.

Thoughts anyone? (By the way just noticed a bug,  it's not recording the last row, will fix it later).

Declare @splitChar varchar(1) = ','

-- Sample CSV below, four columns wide.

Declare @CSV nvarchar(max) ='FileType,NEIC,ins,FileSize
276,4312,FL MCR,9154
276,4312,FL MCR,6532
276,4312,FL MCR,6509'

-- Replace each CRLF with a single carriage return.
Declare @CRLF char(2) = Char(13) + char(10)

if object_Id('tempdb..#table_CSV') is not null drop table #table_CSV
Create Table #table_CSV(
    fakeColumn int
)



set @CSV = Replace(@CSV, @CRLF, char(13))

Declare @FinishedCreatingColumns bit = 0
Declare @TotalLength int = Len(@CSV)
Declare @pos int = 0
Declare @word nvarchar(max) = ''
Declare @Cols nvarchar(max) = '' -- one long string of cols for the INSERT INTO table_CSV (col-1, col-2, col-3)...
Declare  @valuesClause nvarchar(max) = '' -- to be formed as strings, i.e,  VALUES ('val-1', 'val-2', 'val-3')
Declare @AlreadyDroppedTheFakeCol bit = 0
Declare @CarriageReturn char = char(13)
while 1=1
Begin
    set @pos = @pos + 1
    if @pos > @TotalLength break
    Declare @C char = substring(@CSV, @pos, @Pos+1)
    Declare @FoundTheEndOFAWord bit = 0
    if @C = @CarriageReturn or @C = @splitChar  or  @pos = @TotalLength set @FoundTheEndOFAWord =1
    if @FoundTheEndOfAWord =0
    BEgin
        set @word = @word + @C
        continue
    ENd
    Set @ValuesClause = @ValuesClause + '''' + @word + '''' + ','
    if @FinishedCreatingColumns = 0    
    Begin -- Add another column to the table.
        Declare @sql nvarchar(max) = N' Alter Table #table_CSV Add [' + @word + ']  nvarchar(4000)'
        print @sql
        exec sp_ExecuteSql @sql
        set @Cols = @Cols + quoteName(@word) + ','
        set @Word = ''
    End
     if @C <> @CarriageReturn
     Begin
        Set @word = ''
        continue;
   end
   if @AlreadyDroppedTheFakeCol = 0
    Begin
        Alter Table #table_CSV Drop Column FakeColumn
        set @AlreadyDroppedTheFakeCol =1
        set @Cols = substring(@Cols, 1, len(@Cols)-1)
    End
    Set @ValuesClause =    substring(@valuesClause, 1, Len(@Valuesclause)-1)
    set @sql = N' INSERT INTO #table_CSV (' + @cols + ') VALUES(' + @valuesClause + ')'
    print @sql
    if @FinishedCreatingColumns =1    exec sp_ExecuteSql @sql
    Set @FinishedCreatingColumns = 1
    Set @valuesClause = ''
    set @word = ''    
end
select * from #table_CSV


Sort Result set in Custom Order

$
0
0

Hello - Happy Friday everyone !!

I would like result set to be sorted in a custom order, for example, a specific value must appear at top of result set, a specific value must appear at bottom of result set, and others can be sorted in standard order.

Below is the link I found while researching for the possible solution. This works great if I have to sort a specific value to appear at top of result set but I want some specific values to appear at the very bottom as well.

http://sqlandme.com/2013/11/18/sql-server-custom-sorting-in-order-by-clause/

For example:

CountryName

AUSTRALIA

BANGLADESH

CHINA

FRANCE

INDIA

JAPAN

NEW ZEALAND

PAKISTAN

SRI LANKA

UNITED KINGDOM

UNITED STATES

Now based on the popularity you might need a country to appear on top of the list. In order to return results as required, we need to specify a custom sort order in ORDER BY clause. It can be used as below.

The following query will return result set ordered by CountryName, but INDIA at top and CHINA at 2nd "container">

USE [SqlAndMe]
GO
 
SELECTCountryName
FROM   dbo.Country
ORDERBYCASEWHEN CountryName = 'INDIA'THEN'1'
              WHENCountryName = 'CHINA'THEN'2'
              ELSECountryName ENDASC

GO

Result Set:

CountryName

INDIA

CHINA

AUSTRALIA

BANGLADESH

FRANCE

JAPAN

NEW ZEALAND

PAKISTAN

SRI LANKA

UNITED KINGDOM

UNITED STATES

My predicament: Based on the example above, I always want 'India' and 'China' at the TOP and 'Bangladesh' and 'Pakistan' at the bottom. Rest can follow the general sort rule. How do I tweak/approach this? Thank you very much for your help in advance.

Result Set I am anticipating;

INDIA
CHINA
AUSTRALIA
FRANCE
JAPAN
NEW ZEALAND
SRI LANKA
UNITED KINGDOM
UNITED STATES
BANGLADESH
PAKISTAN

This would make my weekend great!!

Regards,


SJ

http://sqlandme.com/2013/11/18/sql-server-custom-sorting-in-order-by-clause/


Sanjeev Jha

Modify the COMPUTED COLUMN to PERSISTED

$
0
0

I have a table which contains a computed column.

Can I alter the table to make the computed column into persisted computed column?

How to separate a column into three different columns

$
0
0

Hi all,

I have a column which has the values as '150/250/555','114/1254/5241','45127/521/102'. So in this way I have a column. Now I need to split this column into three different columns. Say in example '150/250/555', I need to split 150 value into one column, 250 into another column and similarly 555 into 3rd column.

I got for the first column by using this query: select substring(elt.EMPLR_LIAB_TYP_NM,1,CHARINDEX('/',elt.EMPLR_LIAB_TYP_NM)-1) From EMPLOYER_LIABILITY_TYPE elt.

This query is successfully giving me the value of 1 first column which is 150 in example '150/250/555'.

But I am little confused how to do it for 2nd and 3rd columns which should get the values 250 in 2nd column and 555 in 3rd column after '/'. Can anyone help me in this?

Thanks,

Rahul


How to alter column to identity(1,1)

$
0
0

I tried

 

Alter table table1 alter column column1 Identity(1,1);

Alter table table1 ADD CONSTRAINT column1_def Identity(1,1) FOR column1

 

they all can not work,

any idea about this? thanks

 


Invalid SQL Logic - Temp Tables

$
0
0

Could someone explain WHY SQL does not obey logic:

Code that Fails:

IF OBJECT_ID('tempdb..##SCDITL') IS NOT NULL
	DROP TABLE ##SCDITL
IF OBJECT_ID('tempdb..##SCDITLTemp') IS NOT NULL
	DROP TABLE ##SCDITLTemp

SELECT C.ObjectId, L.Name, ROW_NUMBER() OVER (PARTITION BY C.ObjectId ORDER BY L.Name) RNK
INTO ##SCDITLTemp
FROM SlotComponentDef C
		INNER JOIN ITLReport R ON R.SlotComponentDef = C.ObjectId
		INNER JOIN ITL L ON R.ITL = L.ObjectId
		
DECLARE @MaxRNK int
SELECT @MaxRNK = MAX(RNK) FROM ##SCDITLTemp		

IF @MaxRNK > 1 
BEGIN
	CREATE TABLE ##SCDITL (ObjectId UNIQUEIDENTIFIER, LabName NVARCHAR(1024))
	WHILE (@MaxRNK > 0) 
	BEGIN
		-- Other code here not important
		SET @MaxRNK = @MaxRNK - 1
	END
END
ELSE SELECT ObjectId, Name [LabName] INTO ##SCDITL FROM ##SCDITLTemp --this is the line of explosion

SELECT * FROM ##SCDITLTemp
SELECT * FROM ##SCDITL

Error:

Msg 2714, Level 16, State 1, Line 35
There is already an object named '##SCDITL' in the database.

Code that Succeeds:

IF OBJECT_ID('tempdb..##SCDITL') IS NOT NULL
	DROP TABLE ##SCDITL
IF OBJECT_ID('tempdb..##SCDITLTemp') IS NOT NULL
	DROP TABLE ##SCDITLTemp

SELECT C.ObjectId, L.Name, ROW_NUMBER() OVER (PARTITION BY C.ObjectId ORDER BY L.Name) RNK
INTO ##SCDITLTemp
FROM SlotComponentDef C
		INNER JOIN ITLReport R ON R.SlotComponentDef = C.ObjectId
		INNER JOIN ITL L ON R.ITL = L.ObjectId
		
DECLARE @MaxRNK int
SELECT @MaxRNK = MAX(RNK) FROM ##SCDITLTemp		

IF @MaxRNK > 1 
BEGIN
	CREATE TABLE SCDITL (ObjectId UNIQUEIDENTIFIER, LabName NVARCHAR(1024))
	WHILE (@MaxRNK > 0) 
	BEGIN
		-- Other code here not important
		SET @MaxRNK = @MaxRNK - 1
	END
END
ELSE SELECT ObjectId, Name [LabName] INTO SCDITL FROM ##SCDITLTemp

SELECT * FROM ##SCDITLTemp
SELECT * FROM SCDITL

Difference? The Temp Tables ##SCDITL in the first example I changed to being a REGULAR table without the (##).  So why does the global temp table moniker of ## change the behavior of the IF...ELSE clause surrounding the CREATE/SELECT INTO.  What kind of BS backwards logic is operating here that fundamentally ALTERS the behavior of the IF statement executing the CREATE TABLE prior to the IF condition being evaluated simply because the table being created is a temp table?  And yes, I checked, the first example runs without complaint if I comment out the CREATE TABLE line, but by all logic that line SHOULD NOT interfere with the SELECT INTO statement since they are two separate paths and both cannot be executed.

Why was this SNAFU ever allowed past the dev-team door? 

Jaeden "Sifo Dyas" al'Raec Ruiner


"Never Trust a computer. Your brain is smarter than any micro-chip."
PS - Don't mark answers on other people's questions. There are such things as Vacations and Holidays which may reduce timely activity, and until the person asking the question can test your answer, it is not correct just because you think it is. Marking it correct for them often stops other people from even reading the question and possibly providing the real "correct" answer.

Aggregating rows based on contents

$
0
0

I have a query that returns employee shifts for several days. Due to the structure of the database it is possible an employee can have 2 shifts 'back-to-back' which will be returned as separate rows. For example:

Sample Data:

ID      Start                End            
123     01-Aug-14 06:00      01-Aug-14 14:00           
123     01-Aug-14 14:00      01-Aug-14 18:00 
345     01-Aug-14 02:00      01-Aug-14 08:00
456     01-Aug-14 18:00      02-Aug-14 04:00
456     02-Aug-14 04:00      02-Aug-14 06:00          

Desired Result:

ID      Start                End
123     01-Aug-14 06:00      01-Aug-14 18:00 
345     01-Aug-14 02:00      01-Aug-14 08:00
456     01-Aug-14 18:00      02-Aug-14 06:00

I'm looking for the shifts to only be combined when the end (date)time of one is equal to the start (date)time of another for a given employee. 

Any pointers or suggestions greatly appreciated.

Join Data From 3 Tables

$
0
0

I have 3 tables: Table1(Col1,Col2,Col3,Col4); Table2(Col1,Col2,Col3,Col4); Table3(Col1,Col2,Col3,Col4) and they all contain data. Now I want to have a Table4(Col1,Col2,Col3,Col4) and Table4 will contain all data of 3 tables: Table1, Table2, Table3.

Please help me to write a sql query to have the Table4.

Thanks,

 

Database stuck in "In Recovery" mode

$
0
0

Hello. I was doing a query on a database to clear the tables in it. A query that normally takes 2 minutes took the better part of 3 hours...and it wasnt even close to being complete. Therefore, i killed SQL in task manager cause i felt like i had no other choice.

Upon logging back in, the database has been (in Recovery). Accoring to various post i read online, simply detaching it and reattaching it should work fine however, when i try to run queries to detach it i get the following error.

Alter database failed because a lock couldnt be obtained for database <databasename>

I also read that this was due to a connection not being terminated but....everything i tried gives that same lock error. I made sure i was in master, i reset the pc, un-plug network table, tried the commands in the GUI. Nothing's letting me detach said database or remove it from In recovery.

Any help would be appreciated..thank you

Unable to Create Sequence on Table

$
0
0

This is my first time trying to creating a sequence. What's wrong with my syntax? I want to do two things:

(1) Create the sequence on column id2

(2) Set the default value for that column as 'Next Value'

I'm still stuck on part 1

if object_Id('Accounts') is not null	 drop table Accounts
go
create table Accounts(
 Account nvarchar(500),
 id1 int identity(1,1),
 id2 int 
)
go

Create sequence Accounts.id2 
as int
Start with 1
increment by 1;
go
The error says The specified schema name "Accounts" either does not exist or you do not have permission to use it.

Pivot Help?

$
0
0

Hi All,

I need help to write pivot statement for below data 


id year quarter factor   numberic 

10 2012   1      case1     0

10  2012   1      case2     1

10  2012   1      case3     2

10  2012   1      case4    1

10  2012   1      case5     1


Piovot out put

id year quarter case1  case 2 case 3 case 4 case 5
10 2012 1        0       1     2      1      1

Thanks,

CMK...

Primary key auto incrementing by 1000 instead of 1

$
0
0
We have upgraded our SQL 2008 server to 2012 last month.  i've noted since then that many tables that have auto increment primary key bigint field increases by 1 like it should, then for some reason it jumps up by 1000 or even 10000?  i have seed adn auto increment set to 1 but doesnt effect it.  Is there anything that could be causing the next value to jump that much?

Michael Duhon


Compare Comma separated values in single column to multi valued parameter

$
0
0

 I have a column in my table which consists of email id separated by semi colon
email_id 

emailID_column

xx.gmal.com;yy.gmail.com
xx.gmal.com;yy.gmail.com;zz.gmail.com
xx.gmal.com;
yy.gmail.com;zz.gmail.com

and I need to compare with parameters I pass 'yy.gmal.com, zz.gmail.com' IN ssrs

OUTPUT SHOULD BE

xx.gmal.com;yy.gmail.com

xx.gmal.com;yy.gmail.com;zz.gmail.com

yy.gmail.com;zz.gmail.com

if I pass zz.gmail.com

output should be

xx.gmal.com;yy.gmail.com;zz.gmail.com

yy.gmail.com;zz.gmail.com

 

 


Bad execution plans when using parameters, subquery and partition by

$
0
0

We have an issue with the following...

We have this table:

CREATE TABLE dbo.Test (
	Dt date NOT NULL,
	Nm int NOT NULL,
 CONSTRAINT PK_Test PRIMARY KEY CLUSTERED (Dt)
)

This table can have data but it will not matter for this topic.

Consider this query (thanks Tom Phillips for simplifying my question):

declare @date as date = '2013-01-01'
select *
from (
  select Dt,
    row_number() over (partition by Dt order by Nm desc) a
  from Test
  where Dt = @date
) x
go

This query generates an execution plan with a clustered seek.

Our queries however needs the parameter outside of the sub-query:

declare @date as date = '2013-01-01'
select *
from (
  select Dt,
    row_number() over (partition by Dt order by Nm desc) a
  from Test
) x
where Dt = @date
go

The query plan now does a scan followed by a filter on the date.
This is extremely inefficient.

This query plan is the same if you change the subquery into a CTE or a view (which is what we use).

We have this kind of setup all over the place and the only way to generate a good plan is if we use dynamic sql to select data from our views.

Is there any kind of solution for this?

We have tested this (with the same result) on SQL 2008R2, 2012 SP1, 2014 CU1.

Any help is appreciated.

Assistance to Optimize a Stored Procedure which as LEFT OUTER JOIN

$
0
0

Dear Team

Below is my Stored Procedure. It is taking very long (6-10) minutes to execute the part when I did the LEFT join. Attached here is the link to the backup of the database on google drive : https://drive.google.com/file/d/0B5nQIsvTifixUmxXRkwtQW1VWkU/edit?usp=sharing

Please use the SP Script and DB to reproduce my situation

USE [SATURNRPT]
GO
/****** Object:  StoredProcedure [dbo].[PNGudp_Reports_GuardInvoicingBreakUp]    Script Date: 08/16/2014 08:51:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[PNGudp_Reports_GuardInvoicingBreakUp]      
(      
@FROMDATE			DATE,      
@TODATE				DATE,
@BillingPattern		nvarchar(1)='B',
@LocationAutoId		int,
@AreaID				nvarchar(max)='*',
@ClientCode			nvarchar(max)='*'

)      
AS      
  
SET NOCOUNT ON  

-------------------------------------------------------
-- STEP 0. Extract Billing Pattern
-------------------------------------------------------

DECLARE @TmpSalesOrderInit TABLE
(
ClientCode			nvarchar(16),
SoNo				nvarchar(32),
BillingPattern		nvarchar
)


INSERT INTO @TmpSalesOrderInit  
SELECT tt.ClientCode, tt.SoNo,Substring(tt.BillingPattern,1,1) 
						FROM mstSaleOrder tt
	INNER JOIN
							(SELECT SoNo , MAX(SoAmendNo) AS MaxSoAmendNo
							FROM mstSaleOrder WHERE SoStatus='AUTHORIZED' AND ClientCode NOT LIKE '%INTERNAL%'
							GROUP BY SoNo) groupedtt 
						ON tt.SoNo  = groupedtt.SoNo 
						AND tt.SoAmendNo  = groupedtt.MaxSoAmendNo 



DECLARE @TmpSalesOrder TABLE
(
ClientCode			nvarchar(16),
SoNo				nvarchar(32),
BillingPattern		nvarchar
)

IF @BillingPattern='B'
	BEGIN		
		INSERT INTO @TmpSalesOrder 
		Select *  from @TmpSalesOrderInit 
	END
ELSE
	BEGIN
		INSERT INTO @TmpSalesOrder 
		Select *  from @TmpSalesOrderInit WHERE BillingPattern=@BillingPattern 
	END
	


-------------------------------------------------------
-- STEP 1. Extract Deployment Details 1st Step
-------------------------------------------------------

DECLARE @TmpSoDeptShift TABLE
(
SoNo			nvarchar(32),
SoLineNo		int,
PayRatePerHour numeric(18,2),
ChargeRatePerHour numeric(18,2),
ShiftHours		  numeric(18,2),
NoOfPersons		 int
)

		INSERT INTO @TmpSoDeptShift
		SELECT distinct tt.SoNo,SoLineNo,
	CASE
	WHEN tt.MonPayRate <> 0 then tt.MonPayRate
	WHEN tt.TuePayRate <> 0 then tt.TuePayRate
	WHEN tt.WedPayRate <> 0 then tt.WedPayRate
	WHEN tt.ThuPayRate <> 0 then tt.ThuPayRate
	WHEN tt.FriPayRate <> 0 then tt.FriPayRate
	WHEN tt.SatPayRate <> 0 then tt.SatPayRate
	WHEN tt.SunPayRate <> 0 then tt.SunPayRate
	ELSE 0 END As PayRatePerHour,
	CASE
	WHEN tt.MonSellingRate  <> 0 then tt.MonSellingRate
	WHEN tt.TueSellingRate <> 0 then tt.TueSellingRate
	WHEN tt.WedSellingRate <> 0 then tt.WedSellingRate
	WHEN tt.ThuSellingRate <> 0 then tt.ThuSellingRate
	WHEN tt.FriSellingRate <> 0 then tt.FriSellingRate
	WHEN tt.SatSellingRate <> 0 then tt.SatSellingRate
	WHEN tt.SunSellingRate <> 0 then tt.SunSellingRate
	ELSE 0 END  As ChargeRatePerHour,
	CASE
	WHEN DATEDIFF(HOUR,MonTimeFrom,MonTimeTo)  <> 0 then ABS(DATEDIFF(HOUR,MonTimeFrom,MonTimeTo))
	WHEN DATEDIFF(HOUR,TueTimeFrom,TueTimeTo)  <> 0 then ABS(DATEDIFF(HOUR,TueTimeFrom,TueTimeTo))
	WHEN DATEDIFF(HOUR,WedTimeFrom,WedTimeTo)  <> 0 then ABS(DATEDIFF(HOUR,WedTimeFrom,WedTimeTo))
	WHEN DATEDIFF(HOUR,ThuTimeFrom,ThuTimeTo)  <> 0 then ABS(DATEDIFF(HOUR,ThuTimeFrom,ThuTimeTo))
	WHEN DATEDIFF(HOUR,FriTimeFrom,FriTimeTo)  <> 0 then ABS(DATEDIFF(HOUR,FriTimeFrom,FriTimeTo))
	WHEN DATEDIFF(HOUR,SatTimeFrom,SatTimeTo)  <> 0 then ABS(DATEDIFF(HOUR,SatTimeFrom,SatTimeTo))
	WHEN DATEDIFF(HOUR,SunTimeFrom,SunTimeTo)  <> 0 then ABS(DATEDIFF(HOUR,SunTimeFrom,SunTimeTo))
	ELSE 0 END  As ShiftHours,
	CASE
	WHEN tt.MonNoOfPersons   <> 0 then tt.MonNoOfPersons
	WHEN tt.TueNoOfPersons <> 0 then tt.TueNoOfPersons
	WHEN tt.WedNoOfPersons <> 0 then tt.WedNoOfPersons
	WHEN tt.ThuNoOfPersons <> 0 then tt.ThuNoOfPersons
	WHEN tt.FriNoOfPersons <> 0 then tt.FriNoOfPersons
	WHEN tt.SatNoOfPersons <> 0 then tt.SatNoOfPersons
	WHEN tt.SunNoOfPersons <> 0 then tt.SunNoOfPersons
	ELSE 0 END  As NoOfPersons
						FROM mstSaleOrderDeptShift tt
	INNER JOIN
							(SELECT SoNo , MAX(SoAmendNo) AS MaxSoAmendNo
							FROM mstSaleOrderDeptShift
							GROUP BY SoNo) groupedtt 
						ON tt.SoNo  = groupedtt.SoNo 
						AND tt.SoAmendNo  = groupedtt.MaxSoAmendNo 
-------------------------------------------------------
-- STEP 2. Get Number Public Holidays and the Days in Month
-------------------------------------------------------

Declare @TmpTrnHoliday TABLE
(
HolidayDate Date,
HolidayCode nvarchar(10)
)

Insert @TmpTrnHoliday 
exec PNGudp_Reports_GetPublicHolidays @FROMDATE,@TODATE 


 select COUNT(*) as Cnt into #TmpCnt
  from @TmpTrnHoliday  
  insert into #TmpCnt 
  select dbo.PNG_GetDaysInMonth(GetDate()) 
  --select SUM(cnt) from #TmpCnt 
  
-------------------------------------------------------
-- STEP 2. Extract Deployment Details 2nd Step
-------------------------------------------------------

DECLARE @TmpDeployment TABLE
(
SoNo			nvarchar(32),
SoLineNo		int,
PayRatePerHour numeric(18,2),
ChargeRatePerHour numeric(18,2),
ShiftHours		  numeric(18,2),
NoOfPersons		 int,
MonthlyRate		 money
)

INSERT INTO @TmpDeployment 
		select T.*,CASE WHEN M.BillingPattern='F' THEN (T.NoOfPersons*12*377*T.ChargeRatePerHour)/12  ELSE T.NoOfPersons*12*(select SUM(cnt) from #TmpCnt) *T.ChargeRatePerHour END as MonthlyRate from @TmpSoDeptShift T 
		INNER JOIN @TmpSalesOrder M on T.SoNo=M.SoNo			
---------------------------------
-- STEP 1. Extract the Contracted Hours 
-------------------------------------
DECLARE @TmpContract TABLE 
(
LocationAutoId		int,
LocationDesc		nvarchar(50),
AreaID				nvarchar(16),
ClientCode			nvarchar(16),
ClientName			nvarchar(100),
BillingPattern		char(1),
AsmtID			udtAssmtID,
AsmtName			nvarchar(100),
DutyDate			date,
DayNbr				int,
PostAutoID          Numeric(18,0),
PostDesc            nvarchar(200),
ChargeRatePerHour	numeric(18,2),
MonthlyRate			Money,
ContractedHours		int
)

	IF @LocationAutoId = 0 
	BEGIN
		INSERT INTO @TmpContract 
			SELECT     C.LocationAutoId, dbo.mstLocation.LocationDesc, dbo.mstSaleClientDetails.AreaID, C.ClientCode, dbo.mstSaleClient.ClientName,M.BillingPattern , C.AsmtID,
						 dbo.mstSaleClientDetails.AsmtName,  C.Dutydate, DatePart(Day,c.DutyDate) as DayNbr, C.PostAutoID, C.PostDesc, X.ChargeRatePerHour,X.MonthlyRate,SUM(C.ContractedHrs)
			FROM         dbo.tblContractHrs C INNER JOIN
					dbo.mstSaleClient ON C.ClientCode = dbo.mstSaleClient.ClientCode 
					INNER Join  @TmpSalesOrder  M ON C.ClientCode=M.ClientCode and C.SoNo=M.SoNo 
					INNER JOIN 	dbo.mstSaleClientDetails ON C.ClientCode = dbo.mstSaleClientDetails.ClientCode AND 
								C.AsmtId = dbo.mstSaleClientDetails.AsmtId AND C.LocationAutoId = dbo.mstSaleClientDetails.LocationAutoID 
					INNER JOIN 	dbo.mstLocation ON C.LocationAutoId = dbo.mstLocation.LocationAutoID
					INNER JOIN @TmpDeployment  X on C.SoNo= X.SoNo AND C.SoLineNo=X.SoLineNo 
														
			WHERE Dutydate BETWEEN @FROMDATE AND @TODATE AND C.ClientCode NOT LIKE '%INTERNAL%'
			GROUP BY  C.LocationAutoId, dbo.mstLocation.LocationDesc, dbo.mstSaleClientDetails.AreaID, C.ClientCode, dbo.mstSaleClient.ClientName,M.BillingPattern , C.AsmtID,
						 dbo.mstSaleClientDetails.AsmtName,  C.Dutydate, DatePart(Day,c.DutyDate), C.PostAutoID, C.PostDesc, X.ChargeRatePerHour,x.MonthlyRate 
		
	END
	ELSE
	BEGIN
			INSERT INTO @TmpContract 
			SELECT     C.LocationAutoId, dbo.mstLocation.LocationDesc, dbo.mstSaleClientDetails.AreaID, C.ClientCode,dbo.mstSaleClient.ClientName, m.BillingPattern, C.AsmtID,
						dbo.mstSaleClientDetails.AsmtName,C.Dutydate, DatePart(Day,c.DutyDate) as DayNbr, C.PostAutoID, C.PostDesc, X.ChargeRatePerHour,x.MonthlyRate,SUM(C.ContractedHrs)
			FROM         dbo.tblContractHrs C INNER JOIN
					dbo.mstSaleClient ON C.ClientCode = dbo.mstSaleClient.ClientCode INNER JOIN					
					dbo.mstSaleClientDetails ON C.ClientCode = dbo.mstSaleClientDetails.ClientCode AND 
					C.AsmtId = dbo.mstSaleClientDetails.AsmtId AND C.LocationAutoId = dbo.mstSaleClientDetails.LocationAutoID INNER JOIN
					dbo.mstLocation ON C.LocationAutoId = dbo.mstLocation.LocationAutoID
					INNER Join  @TmpSalesOrder  M ON C.ClientCode=M.ClientCode and C.SoNo=M.SoNo
				INNER JOIN @TmpDeployment X on C.SoNo= X.SoNo AND C.SoLineNo=X.SoLineNo 
 					
			WHERE c.LocationAutoId =@LocationAutoId and  Dutydate BETWEEN @FROMDATE AND @TODATE AND C.ClientCode NOT LIKE '%INTERNAL%'
			GROUP BY  C.LocationAutoId, dbo.mstLocation.LocationDesc, dbo.mstSaleClientDetails.AreaID, C.ClientCode, dbo.mstSaleClient.ClientName,M.BillingPattern , C.AsmtID,
						 dbo.mstSaleClientDetails.AsmtName,  C.Dutydate, DatePart(Day,c.DutyDate), C.PostAutoID, C.PostDesc, X.ChargeRatePerHour,x.MonthlyRate		
	END

--select * from @TmpContract 	
---------------------------------
-- STEP 2. Extract Actual Hours
---------------------------------

DECLARE  @TmpRoster TABLE
(
LocationAutoId	int,
ClientCode		nvarchar(16),
BillingPattern		char(1),
AsmtID			udtAssmtID,
DutyDate		Date,
PostAutoID      Numeric(18,0),
ActualHrs		numeric(32,2)
)

  		
IF @LocationAutoId = 0 
	BEGIN	
	INSERT INTO @TmpRoster 
		SELECT     LocationAutoID,R.ClientCode,M.BillingPattern,AsmtID,DutyDate,PostAutoID,
					Sum((DutyMin + 0.00) / 60 ) 
		FROM         dbo.trnRoster R
		INNER JOIN @TmpSalesOrder M on R.ClientCode=M.ClientCode and R.SoNo=M.SoNo 
		WHERE DutyDate BETWEEN @FROMDATE AND @TODATE AND R.ClientCode NOT LIKE '%INTERNAL%'
		GROUP by LocationAutoID,R.ClientCode,m.BillingPattern, AsmtID,DutyDate,	PostAutoID
	END
ELSE
	BEGIN
		INSERT INTO @TmpRoster
		SELECT     LocationAutoID,R.ClientCode,M.BillingPattern,AsmtID,DutyDate,PostAutoID,
					Sum((DutyMin + 0.00) / 60 ) 
		FROM         dbo.trnRoster R
		INNER JOIN @TmpSalesOrder M on R.ClientCode=M.ClientCode and R.SoNo=M.SoNo 
		WHERE DutyDate BETWEEN @FROMDATE AND @TODATE AND R.LocationAutoID=@LocationAutoId AND R.ClientCode NOT LIKE '%INTERNAL%'
		GROUP by LocationAutoID,R.ClientCode,m.BillingPattern, AsmtID,DutyDate,	PostAutoID
	END
 --select * from @TmpRoster 
 ----------------------------------------------
-- STEP 3. Merge Actual Hours with Contracted Hours
------------------------------------------------
 DECLARE @TmpMergeHours TABLE
(
	LocationAutoId	int,
	LocationDesc	nvarchar(50),
	AreaID			nvarchar(16),
	ClientCode		nvarchar(16),
	ClientName		nvarchar(100),
	BillingPattern		char(1),
	AsmtID			udtAssmtID,
	AsmtName		nvarchar(100),
	DutyDate		Date,
	DayNbr				int,
	PostAutoID      Numeric(18,0),
	PostDesc		nvarchar(200),
	ChargeRatePerHour	numeric(18,2),
	MonthlyRate			Money,
	BillableHours		numeric(18,2)
)
	IF @AreaID='*'
		BEGIN	
			INSERT INTO @TmpMergeHours 
					SELECT     C.LocationAutoId,C.LocationDesc,	c.AreaID, C.ClientCode, C.ClientName,  c.BillingPattern,
								C.AsmtID,C.AsmtName,C.DutyDate,c.DayNbr,C.PostAutoID,C.PostDesc,c.ChargeRatePerHour,c.MonthlyRate,
									   case when c.BillingPattern='F' Then C.ContractedHours  else R.ActualHrs end As PayHours
					FROM         @TmpContract C LEFT OUTER  JOIN
								 @TmpRoster R ON C.LocationAutoId = R.LocationAutoID AND 
									C.ClientCode = R.ClientCode AND 
									C.BillingPattern=R.BillingPattern AND
									C.AsmtId = R.AsmtID AND 
									c.DutyDate=r.DutyDate AND	
									C.PostAutoID =R.PostAutoID				
		END
	ELSE
		BEGIN
			INSERT INTO @TmpMergeHours 
					SELECT     C.LocationAutoId,C.LocationDesc,	c.AreaID, C.ClientCode, C.ClientName,  c.BillingPattern,
								C.AsmtID,C.AsmtName,C.DutyDate,c.DayNbr,C.PostAutoID,C.PostDesc,c.ChargeRatePerHour,c.MonthlyRate,
									   case when c.BillingPattern='F' Then C.ContractedHours  else R.ActualHrs end As PayHours
					FROM         @TmpContract C LEFT OUTER  JOIN
								 @TmpRoster R ON C.LocationAutoId = R.LocationAutoID AND 
									C.ClientCode = R.ClientCode AND 
									C.BillingPattern=R.BillingPattern AND
									C.AsmtId = R.AsmtID AND 
									c.DutyDate=r.DutyDate AND	
									C.PostAutoID =R.PostAutoID
					where c.ClientCode in(select part from PNG_SplitString(@ClientCode,',')) and 
					 AreaID in(select part from PNG_SplitString(@AreaID,',')) 					 
		END 
	--SELECT * FRom @TmpMergeHours
 ----------------------------------------------
-- STEP 4. Apply Public Holidays Hours
------------------------------------------------

update @TmpMergeHours 
set BillableHours=BillableHours*2
where BillingPattern='A' and DutyDate in (select HolidayDate from @TmpTrnHoliday) 


---------------------------------
-- STEP 5. Create Pivot table i.e. Format Calender Month
---------------------------------
 
DECLARE @TmpGuardBreakup TABLE
(
LocationAutoId		int,
LocationDesc		nvarchar(100),
AreaID				nvarchar(16),
ClientCode			nvarchar(16),
ClientName			nvarchar(100),
AsmtID				udtAssmtID,
AsmtName			nvarchar(100),
BillingPattern		char(1),
PostAutoID			Numeric(18,0),
PostDesc			nvarchar(200),
ChargeRatePerHour	numeric(18,2),
MonthlyRate			Money,
D01					int,
D02					int,
D03					int,
D04					int,
D05					int,
D06					int,
D07					int,
D08					int,
D09					int,
D10					int,
D11					int,
D12					int,
D13					int,
D14					int,
D15					int,
D16					int,
D17					int,
D18					int,
D19					int,
D20					int,
D21					int,
D22					int,
D23					int,
D24					int,
D25					int,
D26					int,
D27					int,
D28					int,
D29					int,
D30					int,
D31					int
)

INSERT INTO @TmpGuardBreakup		 
 Select * from 
	(
		SELECT     c.LocationAutoId, c.LocationDesc, c.AreaID, c.ClientCode, c.ClientName, c.AsmtID,
						c.AsmtName,c.BillingPattern, C.PostAutoID ,C.PostDesc, C.ChargeRatePerHour,C.MonthlyRate,C.BillableHours,DayNbr
		FROM @TmpMergeHours c													
	) 
	src
	PIVOT
	(
	sum(src.[BillableHours])
	FOR src.DayNbr IN ([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])
	) AS PivotedView


-- -------------------------------
-- --STEP 5. Perform Calculations for Totals and OUTPUT
-------------------------------------
select T.*,c.IsGSTExempted,
(IsNull(D01,0)+IsNull(D02,0)+IsNull(D03,0)+IsNull(D04,0)+IsNull(D05,0)+IsNull(D06,0)+IsNull(D07,0)+IsNull(D08,0)+IsNull(D09,0)+IsNull(D10,0)+IsNull(D11,0)+IsNull(D12,0)+IsNull(D13,0)+IsNull(D14,0)+IsNull(D15,0)+IsNull(D16,0)+IsNull(D17,0)+IsNull(D18,0)+IsNull(D19,0)+IsNull(D20,0)+IsNull(D21,0)+IsNull(D22,0)+IsNull(D23,0)+IsNull(D24,0)+IsNull(D25,0)+IsNull(D26,0)+IsNull(D27,0)+IsNull(D28,0)+IsNull(D29,0)+IsNull(D30,0)+IsNull(D31,0)) as TotalHours
 from @TmpGuardBreakup T
inner join MstClient C on T.ClientCode=C.ClientCode


Marsh Narewec

determining who CREATED/ UPDATED table schema

$
0
0

Hi all,

I have a table called "UserDetails" it has 4 columns and somebody changed one of the column to Non identity .

Id there a way to find out who updated the table schema.

Also i would like to find out who created the table in database.

Thanks in advance.

How to Run SQL scripts on 70 dbs in a single shot.

$
0
0

Hi,

I want to run 2 sql scripts on 70-80 databases, running them individually takes lot of time. Is there a way to run each script on all databases at a time in one shot.


Naveen| Press Yes if the post is useful.


Viewing all 12890 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>