Invalid column name sql ошибка

If you have been using SQL for a good time, you must have come across this issue, which is an invalid column name SQL.

If you have been using SQL for a good time, you must have come across this issue, which is an invalid column name SQL.

Those who are very much into coding and programming, know that this is not a big issue.

Such a minor issue can be solved by just re-looking the code in the column which you want to show in the table.

If you are a beginner and don’t have enough experience in this field, then in this post, I will discuss the below things to make your doubts clear.

  1. Meaning of Invalid Column Name SQL
  2. Invalid Column Name SQL: Reasons
  3. Why a column becomes invalid in SQL?
  4. Methods to overcome Invalid Column Name SQL error

Let’s discuss it one by one.

You may also like: Complete guide on Textmail and Text mail subscriber: 10 Best ways to deal with it

What’s the meaning of Invalid Column Name SQL?

If you are a SQL user, you must have come across these terms.

  1. Table
  2. Column
  3. FROM Clause

This Invalid Column Name SQL error takes place when the column name that you have mentioned in the SQL does not match with the table which is mentioned after FROM Clause.

To show you, I would like to cite an example for better understanding.

Suppose there is a table.

The table name in SQL is student.

And, in the table, we have different column names such as name, mark, age, and address.

I write the below query as below.

select name,mark,aged,adress from student;

Have a look at the array and observe it closely.

If I run the above query, it will not result in anything but an error.

You might ask me why.

I want to again observe carefully the code.

It is written here that-

select name,mark,aged,adress from student;

Mark the word aged.

This exact word was not in our column.

As we mistyped the column name while running the code in SQL, we got an error.

We call it an Invalid Column Name SQL error.

Instead of that code, the correct code would be-

select name,mark,age,adress from student;

Here the word is age and we typed it correctly. There is also no syntax error.

So, what is the meaning of Invalid Column Name SQL?

It simply means that the column that you are referring to in your SQL does not exist.

  • It indicates that you might have misspelled a column.
  • It is also similar to the invalid variable name in different programming languages.

Invalid Column Name SQL: Reasons

Different people face this problem in different contexts.

The come reasons which might have led to Invalid Column Name SQL are given below-

  1. Your column may not exist.
  2. You have deleted your column.
  3. You have misspelled the column name.
  4.  The heading that you have put in the column is not in the required format for SQL.
  5. The column name which you have chosen in your query has changed.

These are the common reasons as to why you get an invalid column name error in SQL(Structured Query Language).

If you think that, you have a different reason other than those reasons which are mentioned above, let us know.

We will try to provide a solution.

Invalid Column Name SQL

Solutions to Invalid Column Name SQL

As I have mentioned earlier that this is not a big issue. So, the solution is simple.

Solution-1: Correct the Column name

In 90% of cases, this works as the best solution.

You just have to look again at your column name and correct it.

In the above-given example, I tried to make you understand with the column name error.

In our case, I types aged instead of age.

So, the result was an error in SQL.

We often call it with the following names.

  1. T SQL Invalid Column Name
  2. TSQL Add column
  3. Invalid Object Name in SQL
  4. SQL invalid column name

If you are someone who is wondering what is invalid object name is SQL, I hope the above example would have answered your question.

Solution-2: Correctly tag the table alias with the column

The SQL error occurs when you wrongly tag the table alias with the column.

So, what you need to do is to make it correct.

You just have to check whether you have correctly tagged the table alias with the column.

If not, do it to get rid of the Invalid Column Name SQL error.

Here is a video for your reference.

Solution-3: Check the Case of the column name

If you are someone who has experience in this field, you know that SQL is case sensitive.

So, you have to take care of these 2 things.

  1. Upper Case letter
  2. Lower Case letter

If your column name is of lower case and your query is in upper case, then that will result in an error and vice-versa also holds true.

So, the only thing that you need to do is to take care of the upper case and lower case letters in SQL to avoid such problems in SQL invalid column name.

Solution-4: Check if you are querying the right table

This is one of those common mistakes that most beginners commit.

Calling a wrong table will obviously result in an SQL server invalid column name error.

So, be sure that you are querying to the right table.

It may happen by mistake but you need to take care of this thing.

Solution-4: Check faulty spellings

This is the last method.

You just have to look once at your column, table, and query.

Check if you have typed anything wrong, which might have included numerical.

If you have typed something wrong, make a correction.

You are good to go.

Invalid Column Name SQL

Conclusion: Invalid Column Name SQL

This is a common error that many newbies face. Even some experienced people face it.

But by looking at the column table, this can be solved in a few seconds.

The solution is very much simple as we knew.

You just have to take care of a few things like spelling, upper case letter, lower case letter, numerics and etc to get rid of this error.

In a nutshell, you just have to follow the above methods if you are facing the Invalid column Name SQL error and get your problem solved. If you are a blogger and interested in knowing how to segregate a post into different pages, you can know here.

I hope this post would have helped you to some extent in solving your problem.

I am trying to enter data into my database, but it is giving me the following error:

Invalid column name

Here’s my code

string connectionString = "Persist Security Info=False;User ID=sa;Password=123;Initial Catalog=AddressBook;Server=Bilal-PC";

using (SqlConnection connection = new SqlConnection(connectionString))
{
  SqlCommand cmd = new SqlCommand();

  cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";
  cmd.CommandType = CommandType.Text;
  cmd.Connection = connection;

  connection.Open();
  cmd.ExecuteNonQuery();
}

tom redfern's user avatar

tom redfern

30k13 gold badges94 silver badges124 bronze badges

asked Dec 5, 2011 at 18:09

Snake's user avatar

4

You probably need quotes around those string fields, but, you should be using parameterized queries!

cmd.CommandText = "INSERT INTO Data ([Name],PhoneNo,Address) VALUES (@name, @phone, @address)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Connection = connection;

Incidentally, your original query could have been fixed like this (note the single quotes):

"VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

but this would have made it vulnerable to SQL Injection attacks since a user could type in

'; drop table users; -- 

into one of your textboxes. Or, more mundanely, poor Daniel O’Reilly would break your query every time.

answered Dec 5, 2011 at 18:11

Adam Rackis's user avatar

Adam RackisAdam Rackis

81.9k55 gold badges267 silver badges392 bronze badges

7

Always try to use parametrized sql query to keep safe from malicious occurrence, so you could rearrange you code as below:

Also make sure that your table has column name matches to Name, PhoneNo ,Address.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address)");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connection;
    cmd.Parameters.AddWithValue("@Name", txtName.Text);
    cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
    cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
    connection.Open();
    cmd.ExecuteNonQuery();
}

answered Dec 5, 2011 at 18:55

Elias Hossain's user avatar

Elias HossainElias Hossain

4,3601 gold badge19 silver badges33 bronze badges

3

Change this line:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";

to this:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

Your insert command is expecting text, and you need single quotes (‘) between the actual value so SQL can understand it as text.

EDIT: For those of you who aren’t happy with this answer, I would like to point out that there is an issue with this code in regards to SQL Injection. When I answered this question I only considered the question in point which was the missing single-quote on his code and I pointed out how to fix it. A much better answer has been posted by Adam (and I voted for it), where he explains the issues with injection and shows a way to prevent. Now relax and be happy guys.

answered Dec 5, 2011 at 18:12

MilkyWayJoe's user avatar

MilkyWayJoeMilkyWayJoe

9,0822 gold badges38 silver badges53 bronze badges

4

You problem is that your string are unquoted. Which mean that they are interpreted by your database engine as a column name.

You need to create parameters in order to pass your value to the query.

 cmd.CommandText = "INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address);";
 cmd.Parameters.AddWithValue("@Name", txtName.Text);
 cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
 cmd.Parameters.AddWithValue("@Address", txtAddress.Text);

answered Dec 5, 2011 at 18:15

Pierre-Alain Vigeant's user avatar

You should never write code that concatenates SQL and parameters as string — this opens up your code to SQL injection which is a really serious security problem.

Use bind params — for a nice howto see here…

answered Dec 5, 2011 at 18:16

Yahia's user avatar

YahiaYahia

69.1k9 gold badges113 silver badges143 bronze badges

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=WKS09SQLEXPRESS;Initial Catalog = StudentManagementSystem;Integrated Security=True");
            SqlCommand insert = new SqlCommand("insert into dbo.StudentRegistration(ID, Name,Age,DateOfBirth,Email,Comment) values(@ID, @Name,@Age,@DateOfBirth,@mail,@comment)", conn);
            insert.Parameters.AddWithValue("@ID", textBox1.Text);
            insert.Parameters.AddWithValue("@Name", textBox2.Text);
            insert.Parameters.AddWithValue("@Age", textBox3.Text);
            insert.Parameters.AddWithValue("@DateOfBirth", textBox4.Text);
            insert.Parameters.AddWithValue("@mail", textBox5.Text);
            insert.Parameters.AddWithValue("@comment", textBox6.Text);

            if (textBox1.Text == string.Empty)
            {
                MessageBox.Show("ID Cannot be Null");
                return;
            }
            else if (textBox2.Text == string.Empty)
            {
                MessageBox.Show("Name Cannot be Null");
                return;
            }


            try
            {
                conn.Open();
                insert.ExecuteNonQuery();
                MessageBox.Show("Register done !");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex.Message);
                conn.Close();
            }
        }

        private void btnRetrive_Click(object sender, RoutedEventArgs e)
        {
            bool temp = false;
            SqlConnection con = new SqlConnection("server=WKS09\SQLEXPRESS;database=StudentManagementSystem;Trusted_Connection=True");
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from dbo.StudentRegistration where ID = '" + textBox1.Text.Trim() + "'", con);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                textBox2.Text = dr.GetString(1);
                textBox3.Text = dr.GetInt32(2).ToString(); 
                textBox4.Text = dr.GetDateTime(3).ToString();
                textBox5.Text = dr.GetString(4);
                textBox6.Text = dr.GetString(5);
                temp = true;
            }
            if (temp == false)
                MessageBox.Show("not found");
            con.Close();
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection connection = new SqlConnection("Data Source=WKS09\SQLEXPRESS;Initial Catalog = StudentManagementSystem;Integrated Security=True");
            string sqlStatement = "DELETE FROM dbo.StudentRegistration WHERE ID = @ID";
            try
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand(sqlStatement, connection);
                cmd.Parameters.AddWithValue("@ID", textBox1.Text);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                MessageBox.Show("Done");
            }
            finally
            {
                Clear();
                connection.Close();
            }
        }

        public void Clear()
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
        }
    }
}

answered Jul 5, 2016 at 12:04

pavithra madhuwanthi's user avatar

Code To insert Data in Access Db using c#

Code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace access_db_csharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   public SqlConnection con = new SqlConnection(@"Place Your connection string");
            
           private void Savebutton_Click(object sender, EventArgs e)
    {
         SqlCommand cmd = new SqlCommand("insert into  Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
                cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
                cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
                cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
                cmd.ExecuteNonQuery();

                }

    private void Form1_Load(object sender, EventArgs e)
    {
        con.ConnectionString = connectionstring;
        con.Open();
    }
}
}

answered Apr 18, 2014 at 18:56

Heemanshu Bhalla's user avatar

Heemanshu BhallaHeemanshu Bhalla

3,5151 gold badge26 silver badges52 bronze badges

You have to use '"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'

Instead of "+texbox1.Text+","+texbox2.Text+","+texbox3.Text+"

Notice the extra single quotes.

Dima Tisnek's user avatar

Dima Tisnek

10.9k4 gold badges64 silver badges120 bronze badges

answered Feb 22, 2017 at 7:46

user7603356's user avatar

Your issue seems to be the Name keyword. Rather use FullName or firstName and lastName, always try and remember to use CamelCase too.

answered Apr 11, 2016 at 13:17

Jonathan Yaniv Ben Avraham's user avatar

1

first create database name «School»
than create table «students» with following columns
1. id
2. name
3. address

now open visual studio and create connection:

namespace school
{
    public partial class Form1 : Form
    {
        SqlConnection scon;


        public Form1()
        {

            InitializeComponent();

            scon = new SqlConnection("Data Source = ABC-PC; trusted_connection = yes; Database = school; connection timeout = 30");
        }

//create command

SqlCommand scom = new SqlCommand("insert into students (id,name,address) values(@id,@name,@address)", scon);

//pass parameters

scom.Parameters.Add("id", SqlDbType.Int);
scom.Parameters["id"].Value = textBox1.Text;

           scom.Parameters.Add("name", SqlDbType.VarChar);
            scom.Parameters["name"].Value = this.textBox2.Text;

            scom.Parameters.Add("address", SqlDbType.VarChar);
            scom.Parameters["address"].Value = this.textBox6.Text;


            scon.Open();
            scom.ExecuteNonQuery();
            scon.Close();
            reset();

        }

also check solution here: http://solutions.musanitech.com/?p=6

answered Sep 9, 2015 at 1:08

Hani Mehdi's user avatar

Hani MehdiHani Mehdi

1874 silver badges9 bronze badges

con = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDbFilename=C:UsersYna Maningding-DulaDocumentsVisual Studio 2010ProjectsLuxuryHotelLuxuryHotelClientsRecords.mdf;Integrated Security=True;User Instance=True");
        con.Open();
        cmd = new SqlCommand("INSERT INTO ClientData ([Last Name], [First Name], [Middle Name], Address, [Email Address], [Contact Number], Nationality, [Arrival Date], [Check-out Date], [Room Type], [Daily Rate], [No of Guests], [No of Rooms]) VALUES (@[Last Name], @[First Name], @[Middle Name], @Address, @[Email Address], @[Contact Number], @Nationality, @[Arrival Date], @[Check-out Date], @[Room Type], @[Daily Rate], @[No of Guests], @[No of Rooms]", con);
        cmd.Parameters.Add("@[Last Name]", txtLName.Text);
        cmd.Parameters.Add("@[First Name]", txtFName.Text);
        cmd.Parameters.Add("@[Middle Name]", txtMName.Text);
        cmd.Parameters.Add("@Address", txtAdd.Text);
        cmd.Parameters.Add("@[Email Address]", txtEmail.Text);
        cmd.Parameters.Add("@[Contact Number]", txtNumber.Text);
        cmd.Parameters.Add("@Nationality", txtNational.Text);
        cmd.Parameters.Add("@[Arrival Date]", txtArrive.Text);
        cmd.Parameters.Add("@[Check-out Date]", txtOut.Text);
        cmd.Parameters.Add("@[Room Type]", txtType.Text);
        cmd.Parameters.Add("@[Daily Rate]", txtRate.Text);
        cmd.Parameters.Add("@[No of Guests]", txtGuest.Text);
        cmd.Parameters.Add("@[No of Rooms]", txtRoom.Text);
        cmd.ExecuteNonQuery();

answered Sep 17, 2016 at 15:40

Yna's user avatar

0

I am working on modifying the existing SQL Server stored procedure. I added two new columns to the table and modified the stored procedure as well to select these two columns as well. Although the columns are available in the table, I keep getting this error:

Invalid column name ‘INCL_GSTAMOUNT’

enter image description here

Can anyone please tell me what’s wrong here?

marc_s's user avatar

marc_s

722k173 gold badges1320 silver badges1443 bronze badges

asked Sep 22, 2013 at 7:41

Kamran Ahmed's user avatar

Kamran AhmedKamran Ahmed

11.4k22 gold badges67 silver badges100 bronze badges

2

Whenever this happens to me, I press Ctrl+Shift+R which refreshes intellisense, close the query window (save if necessary), then start a new session which usually works quite well.

Salah Akbari's user avatar

Salah Akbari

38.8k10 gold badges79 silver badges109 bronze badges

answered Sep 22, 2013 at 8:05

Ric's user avatar

4

Could also happen if putting string in double quotes instead of single.

answered Mar 7, 2014 at 3:30

Harry's user avatar

HarryHarry

1,5951 gold badge10 silver badges12 bronze badges

7

If you are going to ALTER Table column and immediate UPDATE the table including the new column in the same script. Make sure that use GO command to after line of code of alter table as below.

ALTER TABLE Location 
ADD TransitionType SMALLINT NULL
GO   

UPDATE Location SET TransitionType =  4

ALTER TABLE Location 
    ALTER COLUMN TransitionType SMALLINT NOT NULL

answered Oct 29, 2020 at 6:50

dush88c's user avatar

dush88cdush88c

1,8241 gold badge25 silver badges31 bronze badges

0

This error may ALSO occur in encapsulated SQL statements e.g.

DECLARE @tableName nvarchar(20) SET @tableName = ‘GROC’

DECLARE @updtStmt nvarchar(4000)

SET @updtStmt = ‘Update tbProductMaster_’ +@tableName +’ SET
department_str = ‘ + @tableName exec sp_executesql @updtStmt

Only to discover that there are missing quotations to encapsulate the parameter «@tableName» further like the following:

SET @updtStmt = ‘Update tbProductMaster_’ +@tableName +’ SET
department_str = »’ + @tableName + »’ ‘

Thanks

answered Mar 9, 2016 at 9:22

Chagbert's user avatar

ChagbertChagbert

7127 silver badges15 bronze badges

I came here because I was getting this error. And the reason was that I was using double quotes («) instead of single quotes (‘) when giving values for WHERE conditions. Writing this for the future me.

answered Oct 11, 2021 at 19:13

gthuo's user avatar

gthuogthuo

2,2664 gold badges23 silver badges30 bronze badges

Intellisense is not auto refreshed and you should not fully rely on that

answered Sep 22, 2013 at 8:03

Madhivanan's user avatar

MadhivananMadhivanan

13.4k1 gold badge23 silver badges28 bronze badges

I just tried.
If you execute the statement to generate your local table, the tool will accept that this column name exists.
Just mark the table generation statement in your editor window and click execute.

answered Feb 7, 2017 at 7:09

Anderas's user avatar

1

I was getting the same error when creating a view.

Imagine a select query that executes without issue:

select id
from products

Attempting to create a view from the same query would produce an error:

create view app.foobar as
select id
from products

Msg 207, Level 16, State 1, Procedure foobar, Line 2
Invalid column name ‘id’.

For me it turned out to be a scoping issue; note the view is being created in a different schema. Specifying the schema of the products table solved the issue. Ie.. using dbo.products instead of just products.

answered Apr 14, 2016 at 3:46

Molomby's user avatar

MolombyMolomby

5,4832 gold badges32 silver badges27 bronze badges

Following procedure helped me solve this issue but i don’t know why.

  1. Cut the code in question given by the lines in the message
  2. Save the query (e.g. to file)
  3. Paste the code to where it was before
  4. Again save the query

Even if it seems to be the same query executing it did not throw this error

answered Jan 23, 2018 at 9:50

Dreanaught's user avatar

DreanaughtDreanaught

711 silver badge10 bronze badges

1

There can be many things:
First attempt, make a select of this field in its source table;
Check the instance of the sql script window, you may be in a different instance;
Check if your join is correct;
Verify query ambiguity, maybe you are making a wrong table reference
Of these checks, run the T-sql script again

[Image of the script SQL][1]
  [1]: https://i.stack.imgur.com/r59ZY.png`enter code here

answered Dec 19, 2018 at 11:12

Junior Placido's user avatar

I experienced similar problem when running a query from the code (C#) side. The column in the table that was bringing the above error had ‘default value or binding’ (when I checked the table’s design) already added. So I just removed the column and its corresponding value as data being inserted by the query

answered Feb 8, 2022 at 8:44

Timothy Odhiambo's user avatar

1

with refresh table or close and open sql server this work

answered Sep 22, 2013 at 9:41

behzad's user avatar

behzadbehzad

1825 silver badges20 bronze badges

  • Refresh your tables.
  • Restart the SQL server.
  • Look out for the spelling mistakes in Query.

answered Jun 18, 2019 at 8:31

Khizer Amin's user avatar

I noted that, when executing joins, MSSQL will throw «Invalid Column Name» if the table you are joining on is not next to the table you are joining to. I tried specifying table1.row1 and table3.row3, but was still getting the error; it did not go away until I reordered the tables in the query. Apparently, the order of the tables in the statement matters.

+-------------+    +-------------+    +-------------+    
| table1      |    | table2      |    | table3      |    
+-------------+    +-------------+    +-------------+    
| row1 | col1 |    | row2 | col2 |    | row3 | col3 |    
+------+------+    +------+------+    +------+------+    
| ...  | ...  |    | ...  | ...  |    | ...  | ...  |    
+------+------+    +------+------+    +------+------+    

SELECT * FROM table1, table2 LEFT JOIN table3 ON row1 = row3; --throws an error
SELECT * FROM table2, table1 LEFT JOIN table3 ON row1 = row3; --works as expected

answered Oct 25, 2019 at 20:19

Nick Reed's user avatar

Nick ReedNick Reed

4,9814 gold badges16 silver badges37 bronze badges

Not enough rep to comment, so I’ll write a new answer, re: Nick Reed’s answer regarding the ordering of the tables in the query.

The JOIN operation has two operands. In the ON clause, one may only refer to columns from those operands. In Nick’s first example,

SELECT * FROM table1, table2 LEFT JOIN table3 ON row1 = row3; --throws an error

table2 and table3 are the operands of the JOIN, but the ON clause refers to row1, defined in table1. Hence the error.

answered Apr 7, 2021 at 14:03

lot_styx's user avatar

When this happened to me, the good old quit and re-launch SQL server management studio did the trick for me.

answered Mar 9, 2022 at 21:20

NSDumb's user avatar

NSDumbNSDumb

1,71018 silver badges21 bronze badges

I was using DbUp to add a column to a table then in the same script an UPDATE on that column and it said «invalid column <column name>».

Breaking the two statements into separate scripts resolved the issue.

answered Mar 15, 2022 at 2:16

chmoder's user avatar

chmoderchmoder

83611 silver badges19 bronze badges

I am working with Blazor and forgot to use any quotations…

SqlDataAdapter da = new($»select * from table where column = {value}», con);

needed to be

SqlDataAdapter da = new($»select * from table where column = ‘{value}'», con);

Thanks to Harry’s answer above for sending down the right train of thought.

answered May 23, 2022 at 14:19

L__'s user avatar

2

I am working on modifying the existing SQL Server stored procedure. I added two new columns to the table and modified the stored procedure as well to select these two columns as well. Although the columns are available in the table, I keep getting this error:

Invalid column name ‘INCL_GSTAMOUNT’

enter image description here

Can anyone please tell me what’s wrong here?

marc_s's user avatar

marc_s

722k173 gold badges1320 silver badges1443 bronze badges

asked Sep 22, 2013 at 7:41

Kamran Ahmed's user avatar

Kamran AhmedKamran Ahmed

11.4k22 gold badges67 silver badges100 bronze badges

2

Whenever this happens to me, I press Ctrl+Shift+R which refreshes intellisense, close the query window (save if necessary), then start a new session which usually works quite well.

Salah Akbari's user avatar

Salah Akbari

38.8k10 gold badges79 silver badges109 bronze badges

answered Sep 22, 2013 at 8:05

Ric's user avatar

4

Could also happen if putting string in double quotes instead of single.

answered Mar 7, 2014 at 3:30

Harry's user avatar

HarryHarry

1,5951 gold badge10 silver badges12 bronze badges

7

If you are going to ALTER Table column and immediate UPDATE the table including the new column in the same script. Make sure that use GO command to after line of code of alter table as below.

ALTER TABLE Location 
ADD TransitionType SMALLINT NULL
GO   

UPDATE Location SET TransitionType =  4

ALTER TABLE Location 
    ALTER COLUMN TransitionType SMALLINT NOT NULL

answered Oct 29, 2020 at 6:50

dush88c's user avatar

dush88cdush88c

1,8241 gold badge25 silver badges31 bronze badges

0

This error may ALSO occur in encapsulated SQL statements e.g.

DECLARE @tableName nvarchar(20) SET @tableName = ‘GROC’

DECLARE @updtStmt nvarchar(4000)

SET @updtStmt = ‘Update tbProductMaster_’ +@tableName +’ SET
department_str = ‘ + @tableName exec sp_executesql @updtStmt

Only to discover that there are missing quotations to encapsulate the parameter «@tableName» further like the following:

SET @updtStmt = ‘Update tbProductMaster_’ +@tableName +’ SET
department_str = »’ + @tableName + »’ ‘

Thanks

answered Mar 9, 2016 at 9:22

Chagbert's user avatar

ChagbertChagbert

7127 silver badges15 bronze badges

I came here because I was getting this error. And the reason was that I was using double quotes («) instead of single quotes (‘) when giving values for WHERE conditions. Writing this for the future me.

answered Oct 11, 2021 at 19:13

gthuo's user avatar

gthuogthuo

2,2664 gold badges23 silver badges30 bronze badges

Intellisense is not auto refreshed and you should not fully rely on that

answered Sep 22, 2013 at 8:03

Madhivanan's user avatar

MadhivananMadhivanan

13.4k1 gold badge23 silver badges28 bronze badges

I just tried.
If you execute the statement to generate your local table, the tool will accept that this column name exists.
Just mark the table generation statement in your editor window and click execute.

answered Feb 7, 2017 at 7:09

Anderas's user avatar

1

I was getting the same error when creating a view.

Imagine a select query that executes without issue:

select id
from products

Attempting to create a view from the same query would produce an error:

create view app.foobar as
select id
from products

Msg 207, Level 16, State 1, Procedure foobar, Line 2
Invalid column name ‘id’.

For me it turned out to be a scoping issue; note the view is being created in a different schema. Specifying the schema of the products table solved the issue. Ie.. using dbo.products instead of just products.

answered Apr 14, 2016 at 3:46

Molomby's user avatar

MolombyMolomby

5,4832 gold badges32 silver badges27 bronze badges

Following procedure helped me solve this issue but i don’t know why.

  1. Cut the code in question given by the lines in the message
  2. Save the query (e.g. to file)
  3. Paste the code to where it was before
  4. Again save the query

Even if it seems to be the same query executing it did not throw this error

answered Jan 23, 2018 at 9:50

Dreanaught's user avatar

DreanaughtDreanaught

711 silver badge10 bronze badges

1

There can be many things:
First attempt, make a select of this field in its source table;
Check the instance of the sql script window, you may be in a different instance;
Check if your join is correct;
Verify query ambiguity, maybe you are making a wrong table reference
Of these checks, run the T-sql script again

[Image of the script SQL][1]
  [1]: https://i.stack.imgur.com/r59ZY.png`enter code here

answered Dec 19, 2018 at 11:12

Junior Placido's user avatar

I experienced similar problem when running a query from the code (C#) side. The column in the table that was bringing the above error had ‘default value or binding’ (when I checked the table’s design) already added. So I just removed the column and its corresponding value as data being inserted by the query

answered Feb 8, 2022 at 8:44

Timothy Odhiambo's user avatar

1

with refresh table or close and open sql server this work

answered Sep 22, 2013 at 9:41

behzad's user avatar

behzadbehzad

1825 silver badges20 bronze badges

  • Refresh your tables.
  • Restart the SQL server.
  • Look out for the spelling mistakes in Query.

answered Jun 18, 2019 at 8:31

Khizer Amin's user avatar

I noted that, when executing joins, MSSQL will throw «Invalid Column Name» if the table you are joining on is not next to the table you are joining to. I tried specifying table1.row1 and table3.row3, but was still getting the error; it did not go away until I reordered the tables in the query. Apparently, the order of the tables in the statement matters.

+-------------+    +-------------+    +-------------+    
| table1      |    | table2      |    | table3      |    
+-------------+    +-------------+    +-------------+    
| row1 | col1 |    | row2 | col2 |    | row3 | col3 |    
+------+------+    +------+------+    +------+------+    
| ...  | ...  |    | ...  | ...  |    | ...  | ...  |    
+------+------+    +------+------+    +------+------+    

SELECT * FROM table1, table2 LEFT JOIN table3 ON row1 = row3; --throws an error
SELECT * FROM table2, table1 LEFT JOIN table3 ON row1 = row3; --works as expected

answered Oct 25, 2019 at 20:19

Nick Reed's user avatar

Nick ReedNick Reed

4,9814 gold badges16 silver badges37 bronze badges

Not enough rep to comment, so I’ll write a new answer, re: Nick Reed’s answer regarding the ordering of the tables in the query.

The JOIN operation has two operands. In the ON clause, one may only refer to columns from those operands. In Nick’s first example,

SELECT * FROM table1, table2 LEFT JOIN table3 ON row1 = row3; --throws an error

table2 and table3 are the operands of the JOIN, but the ON clause refers to row1, defined in table1. Hence the error.

answered Apr 7, 2021 at 14:03

lot_styx's user avatar

When this happened to me, the good old quit and re-launch SQL server management studio did the trick for me.

answered Mar 9, 2022 at 21:20

NSDumb's user avatar

NSDumbNSDumb

1,71018 silver badges21 bronze badges

I was using DbUp to add a column to a table then in the same script an UPDATE on that column and it said «invalid column <column name>».

Breaking the two statements into separate scripts resolved the issue.

answered Mar 15, 2022 at 2:16

chmoder's user avatar

chmoderchmoder

83611 silver badges19 bronze badges

I am working with Blazor and forgot to use any quotations…

SqlDataAdapter da = new($»select * from table where column = {value}», con);

needed to be

SqlDataAdapter da = new($»select * from table where column = ‘{value}'», con);

Thanks to Harry’s answer above for sending down the right train of thought.

answered May 23, 2022 at 14:19

L__'s user avatar

2

  • Remove From My Forums
  • Question

  • Hello,
    I am using Visual C# 2005 Express Edition and I am trying to connect to an SQL database. I have created the database with the following columns:

    id, first, last, phone, date

    I have created a binding source with a Data Grid View and I am trying to load the data. However, I am getting an «Invalid Column Name» error for NO apparent reason. Here is what my code looks like:

    SqlConnection con = new SqlConnection(«Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\dsAllMembers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True»);
    con.Open();
    if (con.State == ConnectionState.Open)
    {
    System.Console.WriteLine(«So far, so good.»);
    SqlCommand command = new SqlCommand(«SELECT id, first, last, phone, date FROM tblMembers», con);
    SqlDataReader reader = command.ExecuteReader();
    command.ExecuteNonQuery();
    }

    I am 100% sure that the column names are spelled correctly and the database name is correct.  Any suggestions?

    Here is the actual error:
    Invalid column name ‘first’.
    Invalid column name ‘last’.
    Invalid column name ‘phone’.
    Invalid column name ‘date’.

Answers

  • when trying to read data, you dont use the «ExecuteNonQuery», you either fill the data returned into a datatable/dataset via the SqlDataAdapter or as you are doing, using a SqlDataReader.

    Are you also sure that the fields do exist? As well as place, place the square brackets around the field names and tablename to escape it from any special meaning for SQL (keywords).

    what exactly are you trying to do? Read data? Well, depending on how many records there are, you could use a SqlDataReader but if it is a large amount of data, you would be better of using a sqldataAdapter to fill a datatable with results, then say bind it to a datagridview to show the results to the user.

    going with the current code….lets try this…

    System.Console.WriteLine(«So far, so good.»);
    SqlCommand command = new SqlCommand(«SELECT [id], [first], [last], [phone], [date] FROM [tblMembers]», con);
    SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

    while (reader.Read())

    {

       object[] results = new object[] {reader[«id»].ToString(), reader[«first»].ToString(), reader[«phone»].ToString(), reader[«date»].ToString() };

       Console.WriteLine(String.Format(«{0}, {1}, {2}, {3}», results));

    }

  • that should have been CommandBehavior.CloseConnection…my apologies for that.

    its not finding the column name because it doesnt exist in the database and table you are trying to access.

What is an invalid column name sqlInvalid column name SQL error is not a big issue for experienced programmers. Typically, fixing the issues means carefully reviewing your code to flesh out the error. In this write-up, we look at the causes of this error and how to fix them, so, check the article to solve the issue as a pro.

What Is an Invalid Column Name SQL?

An invalid column name error in SQL means that the column name violates the conditions of the column name. If you reference an object that does not exist in the table or the name exists, but you did not reference it correctly, you will get this error.

– Valid Table Name Rules in SQL

A valid SQL name for columns, tables, and databases must follow the rules below:

  • Names must begin with an underscore (_) or an alphabetic character and must contain only alphanumeric characters
  • A name can contain but not begin with 0 – 9, @, #, and $. Nevertheless, names in double-quotes/delimited identifiers can have additional special characters.

– Invalid Column Example

This SQL error pops up when the column name you have mentioned in SQL does not match the name in the table you mention after FROM Clause. To get a better understanding of the error, here is an example:

Suppose you have a table in SQL, and its name is a student. This table has different column names such as Name, Score, Stream, Age, and Gender.

Suppose you write the query as shown below:

Select Name, Score, Stream, Aged, Gender from student;

If you execute the query above, it will throw an error. Take a closer look at the query again – observe each word and compare it to names in the table.

Here is where the problem lies – aged. This word is not in the column of the student SQL file. This simple mistype has led to the SQL error.

Causes of Invalid Column Name Error

This error can occur due to several issues, as shown below. Note that this error behaves similarly to the invalid variable name in other programming languages.

Common causes of this error include:

  • The entered name in the column is not available in the database. If the name is missing from the database, it will not work because SQL will not be able to retrieve it. This can happen if you save the table with a different name from the one you are using to code.
  • Misspelled name. When you misspell a name that SQL is supposed to retrieve, it will not be able to locate it; thus, throwing the error.
  • The column is not in the table altogether. Nothing can be retrieved when the column is absent in the table. So, ensure that you haven’t deleted the table.
  • Using double quotes/apostrophes. Double quotes are not commonly used in SQL, but it varies from one database to another. When dealing with columns in SQL, use single quotes (‘) only. They denote the start and the close of a string. Plus, they make a code more readable.
  • Your heading is not in the required format. Usually, display the header using the default format, and if you want to change them, use the COLUMN command. A column name must be short and cryptic. However, expressions are also used, but they are often hard to understand.

It’s worth mentioning that you can get this error if the chosen column name in your query has changed.

How to Fix Column Name Error

Fixing the error is clear-cut. Nonetheless, you can only solve the problem entirely if you locate the root cause of the issue. In this section, we will mention the issue and its solutions.

– Correct the Column Name

The common cause of this SQL error is an incorrect name. So, about 90% of the time, correcting the column name is the most efficient solution.

How do you apply this solution?

Carefully look over your column name to spot any incorrect names. In the example above, the name age was mistyped as aged, resulting in an error. Upon correcting the name, there want an error.

– Tag the Table Alias With the Column Accurately

You will get this SQL error when you wrongly tag the table alias with the column. The solution is simple, while tagging table alias with a column, ensure you are dealing with the correct ones.

– Check the Case of the Column Name

The SQL Server is, by default, case-insensitive. That means you can use either lower or upper case. But you can tweak settings to make it case-sensitive. So, if you are working with an SQL table, table columns, or database that is case-sensitive, check the case of the column.

Typically, the column name and the query must match in case. For instance, if the column name is in lower case while your query is in upper case, this throws an error. Similarly, the opposite will throw an error.

– Querying the Wrong Table

Querying the wrong table is a pretty common problem among beginners. Ultimately, this will throw an invalid name error. So, carefully select the table to ensure that what you are querying is the table of interest.

– Check Faulty Spellings

When SQL throws an error, check the spellings. The following areas are prone to spelling mistakes:

  • Table
  • Column
  • Query

A mistype may involve adding or removing a letter or even including a numeral. If you suspect something is mistyped, confirm from the original script before executing the code once more.

An omission such as an underscore (_), e.g., [Date Collected] instead of [Date_Collected], will cause a mismatch. Check the invalid column name SQL stored procedure. If the stored procedure has [Date_Collected] while the column name statement is [Date Collected], it will throw an error.

– Use Values With a Single Apostrophe

If your query has double quotes, change them to single quotes. SQL Server treats the double apostrophe as a delimiter for identifiers, such as a column name. This will throw an error when you execute a code. Also, enclose strings in single quotes too.

– Other Invalid Column Name SQL Solutions

The solution includes:

  • Attempt to assign a different table to the column
  • Using a different name for the column that may be present in the database
  • The bug sometimes might cause the error, especially if you use cross-platform database tools such as Azure Studio. So, when you come across the error invalid column name Azure Data Studio may be bugged. In this scenario, update to the latest version of Azure Data Studio. Usually, developers fix lots of bugs costly to ensure that you have an error-free working environment.

Sometimes you might receive an invalid column name ‘False’ or an invalid column name ‘true’. Usually, to get false, enter 0 and to get True, enter 1.

When you remove columns from the script that builds the table, remove the model properties that generated the script. Otherwise, you will get into invalid column name entity framework issues.

SQL Server Invalid Column Name When Column Exists In Table

Sometimes you might receive this error when the column is actually present. This could be due to having two tables with a similar name. The default schema of each database, i.e., the DBO schema, owns one table, while the default schema of the account that connects to SQL Server holds the other table.

Always resolve object reference when you have an unqualified reference to the schema object, e.g., a table not qualified by schema name. The best practice is always to qualify references to schema objects.

Other causes of this error could be:

  • You are not linked to the database you think you are connected
  • You are not connected to the SQL Server instance you think you are.

Double-check your connection strings to ensure that they explicitly specify the SQL instance name and the database name.

How Do You Change a Column Name in SQL?

When you rename a column, it will not automatically rename the reference to that column. Therefore, you must modify objects that reference the renamed column. The easiest way to change the column name is using the SQL Management Studio. This option of changing a column name in the tables has two options:

– Option 1: Object Explorer

  • Open the Object Explorer, and connect to an instance of the Database engine.
  • While still in the Object Explorer, right-click on the table you wish to change the name of columns and select rename.
  • Type a new column name.

– Option 2: Table Designer

  • Open the Object Explorer and right-click on the table you want to rename columns.
  • Select Design
  • Go to Column Name and select the name you wish to change
  • Type a new name
  • Click File menus, and choose table name

Note that you can change a column’s name in the Column Properties tab. Select the column you want to change its name and type a new value for Name.

Remember, making changes can lead to conflict in the SQL Visual Studio or SQL table. To avoid the invalid column name SQL Visual Studio lets you update the data model. Ensure that the update is successful.

Conclusion

SQL allows programmers to access data present within the database using different statements. In this article, we have highlighted a common error that occurs during the process of running quires in SQL. Here are the key points:

  • SQL stores data in columns and rows, and users can update, add, or delete the data in the database.
  • When updating a database, ensure that you add the database table
  • If you have the correct column name but the error persists, try to refresh the environment correctly
  • Always use single quotes in SQL because double quotes will always throw an error

How to fix invalid column name sqlWe have summarized the causes and fixes for SQL invalid column names. We hope that you can now resolve this error easily.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

  • Remove From My Forums
  • Question

  • Hi Experts,

    if

    Exists

    (

    Select Column_Name From Information_Schema.columns

    Where Table_Name = ‘Job_Comments’ AND Column_Name = ‘DeliveryOption’

    )

    Begin

    update Job_Comments set UserAction=‘Order’ where DeliveryOption<>»

    End

    Go

    Above Query is Showing Following Error.

    Msg 207, Level 16, State 1, Line 9

    Invalid column name ‘DeliveryOption’.

    Thanks,

    Abhijeet

Answers

  • This is due to the delayed name resolution mechanism. Try wrapping your UPDATE statement with EXEC(‘…’)

    More info: http://stackoverflow.com/questions/3905910/sql-error-stating-invalid-column-name-when-i-have-verification-if-it-exists-why

    • Proposed as answer by

      Wednesday, December 22, 2010 10:18 PM

    • Marked as answer by
      Kalman Toth
      Monday, December 27, 2010 5:11 AM

  • CallMevlad2 is correct. Sample from SQLUSA easily confirms that due to deferred name resolution, you can not do check and update in one script. The update must be wrapped into EXECUTE in order to succeed.

    USE AdventureWorks;
    SELECT * INTO prod from Production.Product
    GO
    
    IF EXISTS (SELECT *
          FROM  Information_Schema.columns 
          WHERE TABLE_SCHEMA = 'dbo'
             AND Table_Name = 'prod' 
             AND Column_Name = 'ColorDD') 
     BEGIN 
      UPDATE dbo.prod 
      SET  size = 'Order'
      WHERE ColorDD <> '' 
     END
     
    

    Msg 207, Level 16, State 1, Line 8

    Invalid column name ‘Colordd’. 


    Premature optimization is the root of all evil in programming. (c) by Donald Knuth

    Naomi Nosonovsky, Sr. Programmer-Analyst

    My blog

    • Proposed as answer by
      BalmukundMicrosoft employee
      Thursday, December 23, 2010 6:23 AM
    • Marked as answer by
      Kalman Toth
      Monday, December 27, 2010 5:11 AM

Понравилась статья? Поделить с друзьями:
  • Invalid client id код ошибки 15
  • Invalid characters in hostname java как исправить
  • Invalid character in hostname java как исправить
  • Invalid captcha error message
  • Invalid bios image gigabyte как исправить