Saturday 1 October 2016

Compare Id from a Comma separated value in Sql Server

I have a column in which UserIds are stored in a comma separated form (as shown below). Now I have a problem that I need to check whether the current user is available in that list or not. 

I was using split function for this but that was taking too much time. As we need to perform this action on millions of records and table is having 20 other columns which we need to returns. 

Id     UserId 
--  ---------------
1    10,11,12,13    
2    10,13,15,4 

I was using split function for this but that was taking too much time. As we need to perform this action on millions of records and table is having 20 other columns which we need to returns.

Then I found the below solution of my problem. 

SELECT * FROM dbo.History 
WHERE (','+ RTRIM(ShareWith)+',') LIKE '%,'+CAST(@UserId AS VARCHAR)+',%')



Wednesday 13 April 2016

Another Form of Ternary Operator In AngularJS

Once I was working on an AngularJS application. I have a requirement that under ng-repeat I need one object value with comma separated but ‘.’ in last. We can achieve this with the help of ternary operator very easily, but I found something different. This is like 

{{ !$last && ', ' || '.'}}


The above solution resolved the problem also, but the interesting thing is that who it is working. It creates a confusion in my mind. Now I started to find out the best answer for this. In-order to this I created a question on stackoverflow and got many answers all are same. Every explain that it is working as a Ternary operator. 

The best answer that I found is as given below.


It is a form of ternary operator. && returns first operand if it is a falsy value and second operand if first operand is truthy e.g. 1 && 3 will return 3 but 0 && 3 will return 0. Second operator is not evaluated if first is falsy. || is similar but returns first operand if it is truthy and second operand if first is falsy.


So basically cond && val1 || val2 is equivalend to cond ? val1 : val2 under condition that val1 is truthy value. If this is not the case e.g. cond && 0 || 1 this will always return last value 1 in this case.
For readability reasons you should always prefer ternary operator ?: than Boolean shortcircuting operators.