Query Performance Difference Between Sql Server 2005 And 2000
Aug 1, 2007
Hi,
I'm having an issue with a query I'm running on Sql Server 2005. It's a semi-complex query involving an in-line table function and several left outer joins which are joined on to the results of the function call. Two of the left outer joins are then qualified in a where clause of the form where table.Col is not null; the idea is that the final result set contains data that has no match in those two tables.
The problem revolves around a where clause in the function and the last left outer join (ie, one of the ones qualified with where not null). When I alter the where clause of the function to further restrict the result set the function returns, the query times shoots up from 1 second to roughly 2-3 minutes. Note that the time the function takes to complete is not affected. The difference in time is purely down to what the query does with the results the function provides. Also note that the change to the where clause provides a subset of the original data; it does not add any more data (it actually restricts the original resultset by roughly 1000 rows).
I can bring the query speed back down again by removing the last left outer join - this join takes one of the columns from the function, and joins it to a small table - 924 rows. So it appears that this particular join is the cause of the issue, but only when using the resultset generated from the modified function query.
Now, as the thread title alludes, Sql Server 2000 and 2005 handle this differently, or appear to. When I execute this same query on a Sql 2000 machine, there's no apparent time differences, and the data that is returned is as expected. Does anyone have any suggestions as to what might be causing this and how I can fix it? I could simply return the larger resultset and use managed code to filter out the rows I don't want; however, I would like to get to the bottom of this, especially if it's going to effect future queries.
I found an unusual problem between 2000 and 2005 I haven't been ableto decipher from any documentation.The query structure is as follows:select *fromtableA ajointableB b ON a.somekey = b.somekeywherea.type = 'A'and datediff(yyyy, b.someDateField, getdate()) betweena.lowboundary and a.highboundarySome basic facts about the elements and data. The low and high-boundary fields are varchar datatypes. In 2005 (regardless ofcompatibility type I run the database under), the query evaluates theBETWEEN and errors out due to the fact that it is evaluating theDATEDIFF as an integer and finds a non-integer entry in eitherlowboundary or highboundary. I understand and expect this behavior.Obviously, changing the result of the DATEDIFF function to varcharallows the operation to go forth.The odd thing is that there is no "a.type = 'A' " entry, thus thequery wouldn't return anything. In 2000, it seems as though theengine is evaluating the type = 'A' and short-circuiting and in 2005,it is trying to evaluate the entire query OR is there an implicitconversion occuring in 2000 and not in 2005?As I mentioned, the compatibility mode doesn't change how this reacts,but running this on a native 2000 server allows this to happen. Thisparticular code isn't the problem, it's what we might have to contendwith when we migrate this through. Sure, we're going to performregression testing, but I'm concerned about what we would miss.Thanks for any replies.
Dear All,We have a database which contains many tables which have millions ofrecords. When We attach the database with MS SQL Server 2005 StandardEdition Server and run some queries (having joins, filters etc.) thenthey take very long time to execute while when We execute same querieson Enterprise Edition then they run 10 times faster than on standardedition.Our database does not use any features which are present in EnterpriseEdition and not present in Standard Edition. We want to know what arethe differences between Standard Edition and Enterprise Edition forperformance. Why should we go for Enterprise Edition when StandardEdition has all the features required.We are presently using evaluation versions of SQL Server 2005 Standardand Enterprise Editions.Thanks and regards,Nishant Sainihttp://www.simplyjava.com
I have also posted this in microsoft.public.sqlserver.programming.
I have a query which, depending on where I run it from, will either take 10 milliseconds or 10 seconds.
The query works perfectly when run in SQL Server Management Studio... in my database of around 70,000 items it returns the results in around 10ms. It uses all my indexes and indexed views correctly.
However when I run the identical query from my ASP.NET application, it takes around 10 seconds... 1000 times longer. Looking at it in Sql Server Profiler I can't see any difference in the query, except from ASP.NET it needs 62531 reads and from SSMS it needs only 318 reads. If I copy the slow running ASP.NET query from the profiler into SSMS, then it runs quick again. The results returned are the same.
I have provided more details of the query below, but I guess my real question is: What is the best way to debug this? I'm not an expert with SQL Server, so any pointers on where I should start looking to find the difference in how the query is being executed would be a great help.
The query is of the form:
WITH RowPost AS ( SELECT ROW_NUMBER() OVER(ORDER BY DateCreated DESC) AS Row, ItemId, Title, .... FROM Items_View WITH(NOEXPAND) WHERE ItemX >= @minX AND ItemX <= @maxX AND ItemY >= @minY AND ItemY <= @maxY ) SELECT *, (SELECT Count(*) FROM RowPost) AS [Count] FROM RowPost WHERE Row >= @minRow AND Row < @maxRow
Where Items_View is an indexed view, and WITH(NOEXPAND) is being used to force it to use the indexed view (this is optimal). The line beginning "SELECT Count(*)" is to get the total number of results (without having to run the inner query a second time).
This is running against SQL Server Developer Edition.
Executing the stored procedure took 45 seconds. But copying the code to a query window and setting up the variables (instead of parameters), it took 7 seconds.
In the query window, most of the processing cost (86%) is right up front in a "Distinct Sort." But in exec stored procedure, the cost for this step is 11% and the significant costs are in later "Table Scans."
I don't know why SQL Server would choose different execution plans when the code is identical in each.
Hello, all, I started out thinking my problems were elsewhere but as Ihave worked through this I have isolated my problem, currently, as adifference between MSDE and SQL Express 2005 (I'll just call itExpress for simplicity).I have, to try to simplify things, put the exact same DB on twosystems, one running MSDE and one running Express. Both have 2 Ghzprocessors (one Intel, one AMD), both have a decent amount of RAM(Intel system has 1 GB, AMD system has 512 MB), and plenty of GB offree disk space. MSDE is running on the Intel system, Express isrunning on the AMD system. To keep things fair I use the exact sameDB's and query on both systems. The DB's were created on MSDE so Isp_detach_db'd them from MSDE and then sp_attach_db'd them to Express(this is how MS says to do a "side-by-side" upgrade, so it'sacceptable to do so). After fighting problems in performancedifferences in different situations I have narrowed the problem downto this:Executing a simple select statement with join clause on the databasesyields a difference in execution time that is quite great. Using theExpress Management program I can run the query against either system(MSDE or Express, the two systems are connected via crossover cable toeliminate any network problems/issues). When running the queryagainst the MSDE system (which is over the network) I consistently get<20 ms response times on the query. When running the query againstthe Express installation (which is in shared memory) I consistentlyget 700 ms or longer response times. Both times are for the TotalExecution Time.The query is simply this: select db1.* from db1.owner.tablename as db1inner join db2.owner.tablename as db2 on db1.pkey = db2.someid wheredb1.criteria = 3So, gimme all the columns from one table in one DB (local to theinstallation), matching the records in another DB (also local to theinstallation), where one field in the first db matches a field in thesecond db and where, in the first db, one column value = 3.The first table has a total record count of 630 records of which only12 match the where clause. The second table has a total record countof about 2,700 of which only 12 match up on the 12 out of 630.Even though the data is the same and I've done the detach and attach,and even done the sp_updatestats, the difference in execution time isremarkable, in a bad way.Checking the Execution Plan reveals that both queries have the samesteps, but, on the MSDE system the largest consumer in the process isthe Clustered Index Scan of the 630 record table (DB1 in my queryexample), using 85%. The next big consumer is a Clustered Index Seekagainst the other table (2,700 rows), using 15%.The Execution Plan against the Express system reveals basically theexact opposite: 27% going to the Clustered Index Scan of the 630record DB1, and 72% going to the Clustered Index Seek of the 2,700record DB2.I'm sorry to be stupid but I have this information but I don't knowwhat to do with it. The best that I can tell from this is that thisis the source of my problems. My problems are that on my currentsystems that my clients use the data is returned to them faster thanthey can click the mouse and that the new system (that is, when theychose (or are forced by attrition) to move to Vista and thus Express2005) the screen pop is like 1.5 seconds. This creates poor userexperience. Worse, one process I allow the users to do goes fromtaking 14-30 seconds to over 4 minutes (all on the same machine withthe same OS and version of my program, so it's not a machine or OS ormy app problem).Anyway, I hope someone can shed some light on this now that I've paredit down some.Thanks in advance.--HC
The execution time for this query on DB2 v8.0 DBMS one second but I execute it on SQL SERVER 2000 is around 55 second so how i can incease the performance for SQL server
SELECT ACC_KEY1,ACC_STATUS_LAST FROM PSSIG.CLNT_ACCOUNTS INNER JOIN PSSIG.CLNT_CUSTOMERS ON PSSIG.CLNT_ACCOUNTS.CSTMR_OID = PSSIG.CLNT_CUSTOMERS.CSTMR_OID WHERE (PSSIG.CLNT_CUSTOMERS.CSTMR_START_DT >= '1900-1-1 12:00:00') AND (PSSIG.CLNT_CUSTOMERS.CSTMR_END_DT <= '2106-12-31 12:00:00') AND (PSSIG.CLNT_ACCOUNTS.ACC_KEY1 >= '0000000000000') AND (PSSIG.CLNT_ACCOUNTS.ACC_KEY1 <= '9999999999999') AND (PSSIG.CLNT_ACCOUNTS.ACC_STATUS_LAST = 5 ) AND ACC_KEY1 > '0' ORDER BY ACC_KEY1 Note 1: value 5 exist in most of rows about ( 999999/1000000 ) from the table rows count Note 2: the number of rows in each table around 15000000 Note 3: I used the same index structure for both DB2 and SQL server 2000 Note 4: I used some other feature in DB2 that increase the performance but I did not found the alternative for it in SQL server 2000 : a- cardinality varies at run time feature b- include column in index instead of use compound index for ( ACC_KEY1 ,ACC_STATUS_LAST ) columns Note 5 : Enable reverse scan for index
I am having a table with 40 columns and it contains 4 million records. I got the results for one year in 40 secs. After tuning, it is retuning in 24 secs( what i have done is i created index on order by fields).
Can you please suggest me in which way I can increase the performance.
I created a CLR UDF that returns a large number of rows, when I run it from my VPC (XP, SQL Server Developer Edition and 1GB Memory) it takes approx 2 min and 30 secs to start displaying the rows (Using Management Studio), when I run the same query in our development server (Win 2003, SQL Server Enterprise Edition, 8 GB Memory and 8 Processors) it takes more than 15 min to start displaying the results, does anybody have an idea why is this happening?
I am creating an install program and I'm wondering if there is a difference between SQL Server 2000 and MSDE 2000? Do they have different entries in the Registry?
From the documentation that I've read it seems as if they are one and the same.
However, if someone knows how to differentiate between them in the Registry it would be greatly appreciated.
select * from sys.dm_os_performance_counters returns the object names prefixed with "SQLServer:" (e.g. SQLServer:Databases)
It was expected as in other editions also. Issue is that when we try to crate "SQLServer Performance Condition alert", object names in "Object" list comes without the prefix "SQLServer:" (e.g. Databases). Please see the attached snapshots.
I have sql 2000 running with a client database that is about 200 people per day. A VB front end runs it. I have some problems with performance. Would upgrading to Sql 2005 improve my database performance?
Hi, I am developing an web-database application using ASP.net,c# and MSDE. and after the completion of the project i want to deploy the database over the server whichs got sql server professional edition. Are there any changes to be made while deploying it over the server and also will the connection string for MSDE and SQL client the same ? Please do clear me the confusions i have got .. thanks inadvance
Hello everyone,i want to know abt the "Difference between MSDE and SQL Server 2000". For example the features they support, capacity and requirements etc...
We are in the process of upgrading a sql 2000 database over to 2005 and have noticed some substancial performance drops with scalar udfs in 2005.
I have already read the following post http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=491984&SiteID=1 and recognise that udfs are not the most performant option in the first place, but was surprised how much slower these have become on 2005.
Has anyone else had this sort of issue, we really don't want to go away from the udf's but would like to know if there is a design issue within a udf that might be causing this (or even a usage issue). What I am getting as is: Is there certain types of queries, or keywords that should be avoided in udfs on 2005?
A simple example we have is a udf that returns an exchange rate stored in the db, this has parameters of "from currency", "to currency", and date.
SET @ret = ( SELECT TOP 1 TELE_TRANSFER_RATE
FROM dbo.EXCHANGE_RATES
WHERE EXCH_CURRENCY_NO = @from
AND CURRENCY_NO = @to
AND RATE_DATE <= @date
ORDER BY RATE_DATE DESC )
RETURN @ret
And then this is called from a script that returns financials, standard select statement, with udf call in select clause.
Hi guys We are in the process of moving from SQL Server 2000 to 2005. In this process in general I have noticed that performance is better as a result of the move but in a couple of specific cases performance is about 10 time worse as a result of the move and i am wondering if anyone can tell me why.
1) Should I be noticing that calling functions from within a where clause are slower in 2005.
2) Has the and/or logic processing been changed between the different versions.
3) Why does this segment of code run really slow in 2005 but really fast in 2000 (note, i know that its not nice looking but it is pre-existing code from before we came on board and there are more examples of these so its a bit of a change to go through and fix it all up to what it should be but i need to know why before i can move on and as i said i know its not nice and one should expect it to be slow but i specially need to know why it would run fine in 2000 and not on 2005):
..... AND (Deleted = 0) AND (DATEDIFF(d, dbo.GetStartOfDate(ReviewedDate), dbo.GetStartOfDate(GETDATE())) = 3) OR (ProgressPointId = 32) AND (Deleted = 0) AND (DATEDIFF(d, dbo.GetStartOfDate(ReviewedDate), dbo.GetStartOfDate(GETDATE())) = 3) OR (ProgressPointId = 30) AND (Deleted = 0) AND (DATEDIFF(d, dbo.GetStartOfDate(ReviewedDate), dbo.GetStartOfDate(GETDATE())) = 3) ....
I was hoping I wouldn't be another poster with performance issues after migrating to SQl 2005 from SQL 2000 but here I am.
I am in the process of testing out our databases on Sql Server 2005 for migration from SQL Server 2000 and there are certain portions of code that have been affected negatively. I have read thru many of the posts here and have tried out most of the recommendations. I will start out with things I've done and then provide the actual SQL.
1) I have rebuilt all indexes ( using the DBCC REINDEX using the table option). 2) Updated the db engine to latest hot fix (build 3239) that addresses speed related fixes. 3) I also ran sp_createstats using the 'fullscan' option to create stats on all columns of all tables (minus indexed columns) 4) Since nothing seemed to work, I even ran UPDATE STATICS with FULL SCAN on all tables even though I did not need it as the REBUILD woudl have created stats. But I was willing to try anything.
I have confirmed that the execution plans are different even though the data on both sql 2000 and sql 2005 are identical (i put a copy on 2005). The plans themselves are huge as the queries are huge. Here is the query.
SELECT InterimView.* ,TestView.*
FROM View_LabDataExport_TestFormData_55 TestView RIGHT OUTER JOIN ( SELECT ReqView.*, CDView.* FROM View_LabDataExport_FormData_55 ReqView LEFT OUTER JOIN View_LabDataExport_FormData_CD_55 CDView ON ( CDView.DB_SubjectID_CD = ReqView.DB_SUbjectID )
) InterimView
ON ( InterimView.DB_FormID = TestView.DB_FormID_T AND
The above query takes abotu 8 secs to run on 2000 and about 1 minute to run on 2005. This is for a small dataset and on larger datasets this is only going to more pronounced ( as confirmed by other teams that have already migrated in my company). Another point worth mentioning might be if I remove the TestView.* from the select list, it works in 5 to 6 seconds. Is there an issue with Sql 2005 and a large number of columns or anything of that sort? On 2000, the time remains the same , about 8 seconds if I remove this from the select list.
Hi,Simple question: A customer has an application using Access 2000frontend and SQL Server 2000 backend. Data connection is over ODBC.There are almost 250 concurrent users and is growing. Have theysqueezed everything out of Access? Should the move to a VB.Net frontendtaken place ages ago?CheersMike
I cannot get performance out of sql server 2005 through jdbc connections. I have used multiple drivers against 2000 and 2005. 2000 always comes out on top. I installed the os the same, configured the raid array the same, configured the os the same, configured the database the same, installed the software the same, etc.
It seems to come down to the jdbc driver and the way the database handles batch requests from jdbc. Is there some configuration in 2005 that I need to alter to improve the performance of batched inserts through the jdbc driver?
I was hoping I wouldn't be another poster with performance issues after migrating to SQl 2005 from SQL 2000 but here I am.
I am in the process of testing out our databases on Sql Server 2005 for migration from SQL Server 2000 and there are certain portions of code that have been affected negatively. I have read thru many of the posts here and have tried out most of the recommendations. I will start out with things I've done and then provide the actual SQL.
1) I have rebuilt all indexes ( using the DBCC REINDEX using the table option). 2) Updated the db engine to latest hot fix (build 3239) that addresses speed related fixes. 3) I also ran sp_createstats using the 'fullscan' option to create stats on all columns of all tables (minus indexed columns) 4) Since nothing seemed to work, I even ran UPDATE STATICS with FULL SCAN on all tables even though I did not need it as the REBUILD woudl have created stats. But I was willing to try anything.
I have confirmed that the execution plans are different even though the data on both sql 2000 and sql 2005 are identical (i put a copy on 2005). The plans themselves are huge as the queries are huge. Here is the query.
SELECT InterimView.* ,TestView.*
FROM View_LabDataExport_TestFormData_55 TestView RIGHT OUTER JOIN ( SELECT ReqView.*, CDView.* FROM View_LabDataExport_FormData_55 ReqView LEFT OUTER JOIN View_LabDataExport_FormData_CD_55 CDView ON ( CDView.DB_SubjectID_CD = ReqView.DB_SUbjectID )
) InterimView
ON ( InterimView.DB_FormID = TestView.DB_FormID_T AND
The above query takes abotu 8 secs to run on 2000 and about 1 minute to run on 2005. This is for a small dataset and on larger datasets this is only going to more pronounced ( as confirmed by other teams that have already migrated in my company). Another point worth mentioning might be if I remove the TestView.* from the select list, it works in 5 to 6 seconds. Is there an issue with Sql 2005 and a large number of columns or anything of that sort? On 2000, the time remains the same , about 8 seconds if I remove this from the select list.
I have read another thread on this, but I wanted to ask a little more generally, what makes this happen?
The app I got called on is a SQL Server database with an Access front end and a web app front end. The database was on an old machine with SQL Server 2000 and it performed adequately. Then they bought a new high end machine, brought the database over in SQL 2005 and it performs worse than before.
So when I see it, I will check the usual hardware issues but I don't think there will be any.
So the question is, all else being the same, what are the usual things that cause slowness in going from 2000 to 2005?
Do you need to redo indexes? Recompile procs and views?
I did the migration by detaching the database from SQL 2000 running on W2K Pro and attaching it to SQL 2005 running on XP Pro. Some queries with simple aggregate functions such as AVG() have been slowed by at least an order of magnitude. I understand that SQL server can intelligently adapt to improve the performance. I am not sure how much it can improve at this point of time.
if it is possible to run a distributed query against 2000 from 2005, what would the OPENDATASOURCE parameters look like? I'd like to be able to pivot without copying my older 2000 db to 2005 or using linked servers..
For reference, here's an example of a distrib query that reads excel...
ie SELECT * INTO XLImport3 FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'Data Source=C: estxltest.xls;Extended Properties=Excel 8.0')...[Customers$]
SQL 2000: 8.00.2187 x86, 8 way 700mhz, 6GB Ram SQL 2005: 9.00.3042 IA64 2 Way Dual-Core 1.66Mhz 16 GB ram
Symptoms
Querys to the SQL 2005 box from SQL 2000 work but when the query is parameterised with non-literals (@variables) then the query run on the SQL 2005 box excludes any where clause causing the entire table to be returned to the SQL 200 box. When the query is parameterised using literal values the query is executed on SQL 2005 including the where clause.
At first I thought that the "Collation Compatible" setting was the culprit but setting this to 1 made no difference. Other SQL 2000 boxes work as expected and any queries from these using literal and non-literal parameters.
Please, any ideas?
Working
SELECT A.Column FROM linkedServer.IA.dbo.Table Where A.Column = 'value'
Not Working (correctly anyway!)
DECALRE @Value tinyint SET @Value = 22 SELECT A.Column FROM linkedServer.IA.dbo.Table Where A.Column = @value
Hello,I have been searching and reading a lots of information on the microsoft website about the different version of SQL server, but still can not make my decision.In term of performance, is there a real big difference between the workgroup and the standard version? The workgroup is limited to 3 GB of RAM while the standard is unlimited, would that really change the performance if my server has 16Gb or RAM?The price difference is pretty substantial so if could only have to buy the workgroup , it would be better.One more question, regarding the type of licence, my server has 2 processors, could I avoid buying 2 licences and get the Server plus CAL instead. I am using this server to host 4 web-application running on SQL server. Each database is about 15 MB.Thanks in adavance for your advises.Arno
We previously having two servers A and B. Server A is used for updation of data and the data then replicated to server B. Server B is used for
Server A : purpose : used for database updation/ modification SQL Server version : SQL Server 2000 SP 2
Server Z : purpose : used for Reporting SQL Server version : SQL Server 2000 SP 2
We were doing Transactional replication from Server A to Server B.
Last month we have broght another server (Server B) with same hardware configuration but having SQL SERVER 2005 installed. This is to speed up our database update process. We have moved some of the database on this new server so that we can achieve our deadlines.
Server B : purpose : used for database updation/ modification SQL Server version : SQL Server 2005
I have set up the transactional replication from Server B to Server Z and replication works fine. However, the issue is after it is started replicating from this new server (Server B) performance of all the queries reduced a lot.(making my life harder)
I didnt expected this as our reporting server is still SQL server 2000. I have restored the backup of database which was replicated from server A (sql server 2000) and compared execution plan for one of our common query (which is used in most of the reports and which is now taking longer time to provide results)
I found that database which is replicated from Server B (Sql server 2005) is having primary keys. which was not present in the database which replicated from server A(Sql server 2000).
I have then removed the primary key and make the indexes same as previous copy of database(which was replicated from server A) But still the query takes long time.
Execution plan now shows "Table Spool" which was not present in previous copy of database.
Almost every query for this database is taking longer time now.
Can someone suggest me what is wrong and what should I need to fix.
I would like to know if there is any meaningful difference in speed performance between using the DNS ("sql.server.com") or the IP address of the sql-server in the connection string. The advantage of using DNS is that if there is any change in IP, I do not have to change the connection strings, but I do not want to loose speed because of the necessity to resolve the DNS.
Hi Everyone,Apparently, I was being asked on a question, "Why don't we procure adesktop PC to run MS SQL Server 2000 rather than a buying a server?".From a Management point-of-view, buying a desktop PC is much cheaperthan a server. However, I just wanted to understand that is it aviable solution given the database size is something around 200 GB?Equipping with more memory, more storage and a more powerful CPU on adesktop PC could really taking up the role to support the DBMS?Besides this "sensitive" costing concerns, what will be othersdifference in running the SQL Server 2000 on the two differenthardware architecture? For example, IO rate, reliability, RAID-1support, performance, … etc.(Note: The operating system is Microsoft Windows 2000 EnterpriseEdition)Regards,Ambrose
I have a query slower in SQL Server 2005 than in SQL Server 2000. I have a database in SQL 2000, I put it on the same server, but with SQL 2005 and the query take 5 seconds instead of 0 seconds. The DB compatibility is SQL Server 2000 (I tried with 2005 and result is the same). Execution plan seems right and I tried to change some DB options without results. It is weird, when I remove left join on MandatsEx, it take 2 seconds. The view currentEmployeeLevelHistoric returns 45 000 rows and mandatsex has 0 rows.
Here is the sample:
Select ls.EmployeNiveau.pk_EmployeNiveauID as NoNiveau, IsNull(nullif(ls.Traduction.Description, ''), ls.TraductionDefaut.Description) + ' (' + ls.currentLevelHIstoric.NoNiveau + ')' As Nom, ls.currentEmployeeLevelHistoric.DebAssign As DateAssignationDebut, ls.EmployeNiveau.assignmentReason As AssignmentReason, ls.currentEmployeeLevelHistoric.FinAssign As DateAssignationFin, ls.MandatsEx.noDossier, ls.MandatsEx.pk_MandatID, '' As Period, ls.currentEmployeeLevelHistoric.NiveauPrincipal, ls.currentEmployeeLevelHistoric.pk_emplNiveauHisto_Id, ls.EmployeNiveau.fk_NiveauID_Niveaux, ls.EmployeNiveau.No_Ent_leg, IsNull(nullif(TradPere.Description, ''), TradDefautPere.Description) + ' (' + NiveauPere.NoNiveau + ')' As NomSup, ls.EmployeNiveau.No_Ent_leg + ls.EmployeNiveau.no_divisio + ls.EmployeNiveau.no_sec_eco + ls.EmployeNiveau.no_etabli + ls.EmployeNiveau.no_mat as employeeScope, case when ls.mandatExternalisation.fk_mandatID_MandatsEx is null then 2 else 1 end as ContractCategory From ls.currentEmployeeLevelHistoric Inner Join ls.EmployeNiveau on ls.currentEmployeeLevelHistoric.pk_EmployeNiveauID = ls.EmployeNiveau.pk_EmployeNiveauID Inner join ls.currentLevelHistoric On ls.EmployeNiveau.fk_NiveauID_Niveaux = ls.currentLevelHistoric.fk_niveauID_niveaux Left Outer Join ls.TraductionDefaut On ls.currentLevelHIstoric.fk_TraductionID_TraductionDefaut = ls.TraductionDefaut.pk_NoTraduction Left Outer Join ls.Traduction On ls.TraductionDefaut.pk_NoTraduction = ls.Traduction.No_Traduction and ls.Traduction.Langue = 1 Left Join ls.MandatsEx on ls.EmployeNiveau.fk_MandatID_MandatsEx = ls.MandatsEx.pk_MandatID Left Join ls.mandatExternalisation on ls.MandatsEx.pk_MandatID = ls.mandatExternalisation.fk_mandatID_MandatsEx left Join ls.Niveaux as NiveauPere on NiveauPere.niveauID = ls.currentLevelHIstoric.supId Left Outer Join ls.TraductionDefaut As TradDefautPere On NiveauPere.fk_TraductionID_TraductionDefaut = TradDefautPere.pk_NoTraduction Left Outer Join ls.Traduction As TradPere On TradDefautPere.pk_NoTraduction = TradPere.No_Traduction and TradPere.Langue = 1 Where ls.EmployeNiveau.fk_EmploID_Emplos = 345158 and (convert(varchar, ls.currentEmployeeLevelHistoric.DebAssign, 112) <= '20060802' and (ls.currentEmployeeLevelHistoric.FinAssign is null or convert(varchar, ls.currentEmployeeLevelHistoric.FinAssign, 112) >= '20060802'))