简体   繁体   中英

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!

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+''''

Your stored procedure that tries to execute a dynamic sql has a wrong syntax.

DECLARE @ParmDefinition NVARCHAR(2000);

SET @query='SELECT * from '+QUOTENAME(@TableName)+' where Users=@User';
SET @ParmDefinition = N'@User NVARCHAR(20)';
EXECUTE sp_executesql @query, @ParmDefinition, @User = @User;

From the documentation about sp_executesql you could see that a parameter should be used as is inside the dynamic sql text not trying to extract is value and appending the value. After that you should define the parameter for the sp_executesql ( @ParmDefinition ) and set its value ( @User = @User ) as second and third parameter to sp_executesql

查询未正确包含。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM