title: How do I put a CASE statement in a SUBSTRING statement?
body: <p>The purpose of this that I'm trying to compare the usernames of two email addresses and see if they're the same. Really, all I want is for this to work.</p>
  
  <p>When I run the query, all I get is: Invalid length parameter passed to the LEFT or SUBSTRING function.</p>
  
  <p>Note: I changed the query. This better illustrates what I'm trying to do. 
  Note2: I've made the changes so it works properly, but now if the parameter is '', then I get: Invalid length parameter passed to the LEFT or SUBSTRING function.</p>
  
  <pre><code>declare @ReportParameter1 nvarchar(16)
  set @ReportParameter1 = 'manmoon@test1.com'
  declare @ReportParameter2 nvarchar(16)
  set @ReportParameter2 = ''
  select 'test'
  where SUBSTRING (case @ReportParameter1 when '' then 'x@' else @ReportParameter1 end, 1, Charindex('@', case @ReportParameter1 when '' then 'x@' else @ReportParameter1 end) - 1) = 
  SUBSTRING (case @ReportParameter2 when '' then 'x@' else @ReportParameter2 end, 1, Charindex('@', case @ReportParameter2 when '' then 'x@' else @ReportParameter2 end) - 1)
  </code></pre>
  
  <p>Here's the where clause I used to fix the problem. However, this will teach me to be more careful when copying and pasting.</p>
  
  <pre><code>WHERE (substring(@ReportParameter1, 1, case when (CHARINDEX('@', @ReportParameter1) - 1) &lt; 1 then 1 else CHARINDEX('@', @ReportParameter1) - 1 end) = SUBSTRING(@ReportParameter2, 1, CHARINDEX('@', @ReportParameter2) - 1))
  </code></pre>