Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think your problem is because you are not specifying the size on your varchar (which is defaulting to 1). This is resulting in the input and the output being truncated to a single character. (You were also missing an <code>@</code> on your variable inside the function.)</p> <p>So <code>PRINT dbo.SizeExample('16-18')</code> will print <code>'B'</code> (which is not only truncated, it's also not the answer you probably want, which is <code>'1'</code>)</p> <p>Try instead:</p> <pre><code>CREATE FUNCTION MaraSizeExample ( @ms varchar(5) ) RETURNS varchar(3) AS BEGIN RETURN CASE @ms WHEN '16-18' THEN '1' WHEN '18-20' THEN '2' WHEN '20-22' THEN '3' WHEN '22+' THEN '4' WHEN '24+' THEN '5' WHEN '14-16' THEN '7' ELSE 'BAD' END END </code></pre> <ol> <li><p><code>CASE</code> is just a searched (or lookup) expression - you cannot <code>RETURN</code> from inside it - it's kind of like like <code>IIF()</code> in VB or <code>IF()</code> in Excel. The earlier answer basically explained that.</p></li> <li><p><code>VARCHAR</code> means <code>VARCHAR(1)</code>, so you would get truncation - i.e. you'd never see <code>'BAD'</code> coming out, only <code>'B'</code>. I'm not sure why you don't get a truncation warning when it happens like you get on some <code>SQL</code> <code>INSERT</code>, but there you go.</p></li> <li><p><code>@ms</code> is your variable's name. I'm not sure why ms would be accepted unless there was some other database object by that name (a table?) - and even then it wouldn't be. All variables and parameters in <code>T-SQL</code> are prefixed with <code>@</code> like this.</p></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload