Search code examples
c#wpfstored-proceduressyntax-errorsql-server-2014-express

Invalid column name on stored procedure


Here is my stored procedure in SQL Server 2014:

CREATE PROCEDURE [dbo].[spSelectUserFromProfileUsers]
    @TableName NVARCHAR(20),
    @User NVARCHAR(20)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @query NVARCHAR(MAX);
    SET @query = 'SELECT * FROM ' + QUOTENAME(@TableName) + ' WHERE  Users =' + @User

    EXECUTE sp_executesql @query
END

and here is my code in Visual Studio:

if (TableFunctions.doesTableExist(ComboBoxSelectedProfile.SelectedItem + "Users", dbConnectionString))
{
    // DynamicSQL
    using (SqlCommand command = new SqlCommand("spSelectUserFromProfileUsers", connection))
    {
        command.CommandType = CommandType.StoredProcedure;

        command.Parameters.AddWithValue("@TableName", ComboBoxSelectedProfile.SelectedItem + "Users");
        command.Parameters.AddWithValue("@User", TextBoxUserName.Text);

        command.ExecuteNonQuery();
    }
}

and I'm getting the error:

Invalid column name /Text that I entered the textbox/

I've been looking for a solution a long time and I can't find anything, I'll appreciate your help very much!


Solution

  • You need to make sure that your Users value is inside quotes. As it's a sql and there are only single quotes available, you have to do it in that strange way.

    SET @query='SELECT * from '+QUOTENAME(@TableName)+' where Users='''+@User+''''