Note that there are some explanatory texts on larger screens.

plurals
  1. POOptional parameters in SQL stored procedure
    primarykey
    data
    text
    <p>I am trying to create a stored procedure that has optional parameters. I followed the instructions listed <a href="http://weblogs.asp.net/stanleygu/archive/2010/02/08/solution-5-implementing-optional-parameters-in-t-sql-stored-procedures.aspx" rel="nofollow noreferrer">here</a>. I also referenced this <a href="https://stackoverflow.com/questions/3415582/how-can-i-use-optional-parameters-in-a-t-sql-stored-procedure">SO question</a>. However I keep receiving the following error:</p> <blockquote> <p>Error converting data type varchar to int.</p> </blockquote> <p>It works when I execute it as </p> <pre><code>EXEC sp_get_user {id#} </code></pre> <p>or </p> <pre><code>EXEC sp_get_user NULL, {username} </code></pre> <p>but fails with </p> <pre><code>EXEC sp_get_user {username} </code></pre> <p><strong>Stored Procedure</strong></p> <pre><code>@id int = NULL, @username nvarchar(50) = NULL SELECT username = COALESCE(a.Username, b.Username), password = COALESCE(a.Password, b.Password), signup_date = COALESCE(a.SignedUpOn, b.Signup_Date) FROM table1 a FULL OUTER JOIN table 2 b ON a.ID = b.ID WHERE ((a.ID = @id OR @id IS NULL) AND (a.Username = @username OR @username IS NULL) OR (b.ID = @id OR @id IS NULL) AND (b.Username = @username OR @username IS NULL)) </code></pre> <p>I have tried adding the <code>OPTION(RECOMPILE)</code> and had no success. I want to make this dynamic so other developers can call this SP without having to specify all parameters each time. They will be connecting via LINQ if that makes a difference.</p>
    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.
 

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