Wednesday, March 7, 2012

execute scalar question

Im using the following code in my application. Is it redundent to add the "Top 1" to the select or does it help performance? Thanks

string strSQL ="SELECT TOP 1 c.CusId " +"FROM COCUS c " +"LEFT JOIN CONOTITM n ON c.NotId = n.NotId " +"WHERE c.CusId NOT IN(SELECT CusId FROM RDK_PROSPECT_LOCK WHERE EmpId <> '" + USER.ID() +"') " +"ORDER BY n.DateUpdate, c.DateUpdate ASC";string strCusID = RDK.DATA.ReturnScalar(strSQL);
If your query can only ever return one row then it won't be necessary. If it can return more than one row then adding the Top 1 would probably help as otherwise you would be sending back multiple rows that would then be discarded apart from the first column in the first row. If optimum efficiency is what you are after I'd suggest using a stored procedure with an output parameter if you only need to return one value.|||

Yes, it will help performance. Not only does it guarantee that only a single row will be returned, but it also allows SQL Server to optimize it's query.

It's similiar to asking "Get me the lowest..." and "Get me all of them and order them by...". The first one allows SQL Server to look for the lowest and once it finds it, then stop.

No comments:

Post a Comment