Ошибка недопустимое имя столбца sql

I suspect that you have two tables with the same name. One is owned by the schema ‘dbo’ (dbo.PerfDiag), and the other is owned by the default schema of the account used to connect to SQL Server (something like userid.PerfDiag).

When you have an unqualified reference to a schema object (such as a table) — one not qualified by schema name — the object reference must be resolved. Name resolution occurs by searching in the following sequence for an object of the appropriate type (table) with the specified name. The name resolves to the first match:

  • Under the default schema of the user.
  • Under the schema ‘dbo’.

The unqualified reference is bound to the first match in the above sequence.

As a general recommended practice, one should always qualify references to schema objects, for performance reasons:

  • An unqualified reference may invalidate a cached execution plan for the stored procedure or query, since the schema to which the reference was bound may change depending on the credentials executing the stored procedure or query. This results in recompilation of the query/stored procedure, a performance hit. Recompilations cause compile locks to be taken out, blocking others from accessing the needed resource(s).

  • Name resolution slows down query execution as two probes must be made to resolve to the likely version of the object (that owned by ‘dbo’). This is the usual case. The only time a single probe will resolve the name is if the current user owns an object of the specified name and type.

[Edited to further note]

The other possibilities are (in no particular order):

  • You aren’t connected to the database you think you are.
  • You aren’t connected to the SQL Server instance you think you are.

Double check your connect strings and ensure that they explicitly specify the SQL Server instance name and the database name.

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

30.6k14 gold badges91 silver badges126 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

82.6k56 gold badges271 silver badges393 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,4101 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,0922 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.7k9 gold badges116 silver badges144 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=WKS09\SQLEXPRESS;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,6031 gold badge27 silver badges53 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

11.3k4 gold badges68 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

1974 silver badges9 bronze badges

con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Yna Maningding-Dula\Documents\Visual Studio 2010\Projects\LuxuryHotel\LuxuryHotel\ClientsRecords.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 suspect that you have two tables with the same name. One is owned by the schema ‘dbo’ (dbo.PerfDiag), and the other is owned by the default schema of the account used to connect to SQL Server (something like userid.PerfDiag).

When you have an unqualified reference to a schema object (such as a table) — one not qualified by schema name — the object reference must be resolved. Name resolution occurs by searching in the following sequence for an object of the appropriate type (table) with the specified name. The name resolves to the first match:

  • Under the default schema of the user.
  • Under the schema ‘dbo’.

The unqualified reference is bound to the first match in the above sequence.

As a general recommended practice, one should always qualify references to schema objects, for performance reasons:

  • An unqualified reference may invalidate a cached execution plan for the stored procedure or query, since the schema to which the reference was bound may change depending on the credentials executing the stored procedure or query. This results in recompilation of the query/stored procedure, a performance hit. Recompilations cause compile locks to be taken out, blocking others from accessing the needed resource(s).

  • Name resolution slows down query execution as two probes must be made to resolve to the likely version of the object (that owned by ‘dbo’). This is the usual case. The only time a single probe will resolve the name is if the current user owns an object of the specified name and type.

[Edited to further note]

The other possibilities are (in no particular order):

  • You aren’t connected to the database you think you are.
  • You aren’t connected to the SQL Server instance you think you are.

Double check your connect strings and ensure that they explicitly specify the SQL Server instance name and the database name.

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

725k174 gold badges1326 silver badges1449 bronze badges

asked Sep 22, 2013 at 7:41

Kamran Ahmed's user avatar

Kamran AhmedKamran Ahmed

11.6k22 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

39k10 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,6551 gold badge11 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,8681 gold badge26 silver badges31 bronze badges

0

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,3064 gold badges23 silver badges30 bronze badges

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

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 badges29 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,5812 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

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

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,9914 gold badges17 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,72018 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

85611 silver badges19 bronze badges

I’m developing SQL script, using SSMS, which makes some changes in database:

USE MyDatabase;

BEGIN TRANSACTION;

-- some statements

PRINT(N'#1');

IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'Table1' AND COLUMN_NAME = 'Table2_Id'))
BEGIN
    ALTER TABLE [dbo].[Table1] DROP CONSTRAINT [FK_Table1_Table2_Table2_Id];
    ALTER TABLE [dbo].[Table1] DROP COLUMN [Table2_Id];
    DROP TABLE [dbo].[Table2];

    PRINT(N'Table2 was dropped.');
END

PRINT(N'#2');

IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'Table2'))
BEGIN
    CREATE TABLE [dbo].[Table2]
    (
        [Id] INT NOT NULL PRIMARY KEY IDENTITY,
        [Number] INT NOT NULL UNIQUE,
        [Name] NVARCHAR(200) NOT NULL,
        [RowVersion] TIMESTAMP NOT NULL
    );
PRINT(N'Table2 was re-created.');
    INSERT INTO [dbo].[Table2]([Number], [Name]) VALUES(-1, N'Default value');
PRINT(N'Default value was inserted in Table2.');
END

-- some statements

COMMIT TRANSACTION;

If Table1 has a column, named Table2_Id, then database has two tables (Table1 and Table2) and a foreign key relationship between them. In that case, I need to:

  • drop foreign key relationship FK_Table1_Table2_Table2_Id;
  • drop foreign key column Table1.Table2_Id;
  • drop Table2;
  • re-create Table2, using new table schema;
  • insert some default value in Table2.

When I’m trying to execute this script, I’m getting these errors:

Msg 207, Level 16, State 1, Line 262 Invalid column name ‘Number’.
Msg 207, Level 16, State 1, Line 262 Invalid column name ‘Name’.

Looks like SQL Server uses old schema for Table2 (which indeed hasn’t these columns), but how is this possible, if the table has just created with new schema?

What am I doing wrong?

Server version is SQL Server 2012 (SP1) — 11.0.3128.0 (X64).

UPDATE.

I’ve added PRINT calls (see script above). There’s nothing in message window, except error messages. So, the script isn’t being executed… What’s going on??



Я работаю над изменением существующей хранимой процедуры SQL Server. Я добавил два новых столбца в таблицу и также изменил хранимую процедуру, чтобы выбрать эти два столбца. Хотя столбцы доступны в таблице SQL Server продолжает давать эту ошибку:

недопустимое имя столбца ‘INCL_GSTAMOUNT’

enter image description here

может кто-нибудь пожалуйста, скажите мне, что тут не так?


1670  


9  

9 ответов:

всякий раз, когда это происходит со мной, я нажимаю Ctrl+ Shift+R обновления intellisense, закройте окно запроса (сохранить при необходимости), а затем запустите новый сеанс, который обычно работает довольно хорошо.

также может произойти, если положить строку в двойные кавычки вместо одинарных.

Intellisense не обновляется автоматически, и вы не должны полностью полагаться на это

эта ошибка также может возникать в инкапсулированных инструкциях SQL, например

объявить @tableName nvarchar (20) SET @tableName = ‘GROC’

объявить @updtStmt nvarchar (4000)

SET @updtStmt = ‘Update tbProductMaster_’ [email protected] + ‘ SET
department_str = ‘ + @tableName exec sp_executesql @updtStmt

только чтобы обнаружить, что отсутствуют цитаты для инкапсуляции параметра «@tableName » далее, как следующее:

SET @updtStmt = ‘Update tbProductMaster_’ [email protected] + ‘ SET
department_str = «‘ + @tableName+»»

спасибо

я получаю ту же ошибку при создании представления.

представьте себе запрос select, который выполняется без проблем:

select id
from products

попытка создать представление из того же запроса приведет к ошибке:

create view app.foobar as
select id
from products

Msg 207, Уровень 16, состояние 1, процедура foobar, строка 2
Недопустимое имя столбца «id».

для меня это оказалось проблемой области видимости; обратите внимание, что представление создается в другой схеме. Указание схема из products таблица решила проблему. То есть.. используя просто products.

с обновить таблицу или закрыть и открыть sql server эта работа

У меня была похожая проблема.

проблема заключалась в том, что в таблице был триггер, который записывал изменения в таблицу журнала аудита. В таблице журнала аудита отсутствовали столбцы.

следующая процедура помогла мне решить эту проблему, но я не знаю, почему.

  1. вырезать код, о котором идет речь, заданный строками в сообщении
  2. сохраните запрос (например, в файл)
  3. вставьте код туда, где он был раньше
  4. снова сохраните запрос

даже если это, кажется, тот же запрос, выполняющий его не бросил эту ошибку

Я просто попробовал.
Если вы выполните инструкцию для создания локальной таблицы, инструмент примет, что это имя столбца существует.
Просто отметьте оператор генерации таблицы в окне редактора и нажмите кнопку Выполнить.

I am trying to UPDATE a specific column within a table, but I get an error due to the fact that when SQL compiles, the column name IssueTimeUTC does not actually exist. Here is my sample code:

   WHILE  @startissuetime<='23:30'
        BEGIN
        ALTER TABLE Intraday_Forecast_temp
            ADD IssueTimeUTC SMALLDATETIME 

            UPDATE Intraday_Forecast_temp
            SET IssueTimeUTC=CAST(@tempdate AS SMALLDATETIME)
            WHERE DateTimeUTC>CAST(@tempdate AS SMALLDATETIME)

            UPDATE Intraday_Forecast_temp
            SET IssueTimeUTC=Dateadd(d,-1,CAST(@tempdate AS SMALLDATETIME))
            WHERE

DateTimeUTC<=CAST(@tempdate AS SMALLDATETIME)
END

I have read multiple similar posts, but I cannot make anything work therefore I am kindly asking you if you could help me.

The error I get is this:

Msg 207, Level 16, State 1, Line 56 Invalid column name ‘IssueTimeUTC’.

Update: So basically I was not able to find an exact solution to this specific problem but I just found a way to go »around» the problem instead. So this is the updated code I used.

WHILE  @startissuetime<='23:30'
    BEGIN
        ALTER TABLE Intraday_Forecast_temp
        DROP COLUMN IssueTimeUTC 
        --------
        BULK INSERT..... 
        --------
        ALTER TABLE Intraday_Forecast_temp
        ADD IssueTimeUTC SMALLDATETIME 

        UPDATE Intraday_Forecast_temp
        SET IssueTimeUTC=CAST(@tempdate AS SMALLDATETIME)
        WHERE DateTimeUTC>CAST(@tempdate AS SMALLDATETIME)

        UPDATE Intraday_Forecast_temp
        SET IssueTimeUTC=Dateadd(d,-1,CAST(@tempdate AS SMALLDATETIME))
        WHERE DateTimeUTC<=CAST(@tempdate AS SMALLDATETIME)
    END

I know that this is not probably the most elegant solution but I initially defined the Intraday_Forecast_temp table WITH the column IssueTimeUTC , then I drop it and add it again. This way, SQL stop complaining that the column does not exist upon compilation :)

  • Remove From My Forums
  • Question

  • Hello, I am new to Visual C# and MSDN.  My searches have yielded little help, so I’m hoping a post will.

    I am playing around with the Northwind sample DB and have a simple app that returns each customer and the orders made by that customer:

    SqlDataAdapter custAdapter = new SqlDataAdapter(«SELECT * FROM dbo.Customers», customerConnection);
    OleDbDataAdapter ordAdapter = new OleDbDataAdapter(«SELECT * FROM Orders», orderConnection);       


    In trying to hard code a query for the orders belonging to a specific customer, I made the following addition (in green):

    SqlDataAdapter custAdapter = new SqlDataAdapter(«SELECT * FROM dbo.Customers WHERE CustomerID = ANATR», customerConnection);

    This generated an error:

    Exception Details: System.Data.SqlClient.SqlException: Invalid column name ‘ANATR’.

    What is the correct way to go about doing this? Ultimately, I would like to put in a variable that allows me to enter any customer’s name/id and see all the associated orders.

    Any help or advice is appreciated!

    • Edited by

      Friday, June 27, 2008 3:31 PM
      Problem solved

Answers

  • Tables[«Customers»] is a table IN MEMORY which holds all the customers with CustomerID == ‘ANATR’ (which should be just one). Tables[«Orders»] is a table in memory which holds all orders for all customers.  You are trying to join the two tables.  But there are orders in Tables[«Orders»] for customers which are not in Tables[«Customers»]. That’s the problem you are having.

    change the second line to

    OleDbDataAdapter ordAdapter = new OleDbDataAdapter(«SELECT * FROM Orders WHERE CustomerID = ‘ANATR’», orderConnection);

    should solve the problem.

    Both the problems  you’ve had are far more related to SQL than C#, so  that’s probably should be where you spend your study time.


    Truth, James (http://www.honestillusion.com)

    • Proposed as answer by
      Papy Normand
      Sunday, June 29, 2008 12:03 PM
    • Marked as answer by
      jack 321
      Tuesday, July 1, 2008 5:54 AM

OneManPunch

0 / 0 / 0

Регистрация: 20.03.2020

Сообщений: 18

1

Недопустимое имя столбца

15.05.2021, 14:14. Показов 3351. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте. При написании запроса, возникает ошибка. Никак не могу понять в чём проблема

SQL
1
2
3
4
SELECT Код_заказчика, Дата_поставки, Количество, Стоимость_единицы_продукции, [Количество]*[Стоимость_единицы_продукции] AS 'Стоимость заказа', 
'0,2' * [Стоимость заказа] AS 'ПДВ 20%', [Стоимость заказа] + [ПДВ 20%] AS 'К оплате'
FROM Узлы INNER JOIN Заказчик 
ON Узлы.Код_узда = Код_узла;

«Недопустимое имя столбца «Стоимость заказа».
Сообщение 207, уровень 16, состояние 1, строка 2
Недопустимое имя столбца «Стоимость заказа».
Сообщение 207, уровень 16, состояние 1, строка 2
Недопустимое имя столбца «ПДВ 20%».».



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

15.05.2021, 14:14

Ответы с готовыми решениями:

Недопустимое имя столбца
Доброго времени суток!

В общем, в БД есть таблица, один столбец которой — дата в формате…

Недопустимое имя столбца
Выскакивает ошибка &quot;Недопустимое имя столбца &quot;Всего&quot;.
Уже всю голову сломал, не могу понять в чем…

Недопустимое имя столбца
Подскажите, как исправить данную ошибку, внешний ключ прописал

go
CREATE PROCEDURE IZM_Tovar…

Недопустимое имя столбца…
В SQL Server Management Studio 2010 набрала код….
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER…

3

Эксперт MS Access

17320 / 7146 / 1614

Регистрация: 21.06.2012

Сообщений: 13,488

15.05.2021, 15:55

2

Вместо ‘Стоимость заказа’ написать [Стоимость заказа] не пробовали.

Не по теме:

По всей видимости навеяно MySQL, но и там ‘ другие `



0



3522 / 2145 / 679

Регистрация: 29.05.2013

Сообщений: 9,153

15.05.2021, 16:20

3

Я тут вижу 2 непонятки:
1. ‘0,2’ * [Стоимость заказа] т.е. строка умножается на число. Уже странно.
2. [ПДВ 20%] — Процент относится к служебным символам и запрещен для использования в имени поля или псевдониме.



0



invm

3344 / 2045 / 731

Регистрация: 02.06.2013

Сообщений: 5,026

15.05.2021, 17:39

4

Цитата
Сообщение от OneManPunch
Посмотреть сообщение

Никак не могу понять в чём проблема

Проблема — в нежелании читать документацию.
https://docs.microsoft.com/ru-… rver-ver15
См. раздел «Логический порядок обработки инструкции SELECT»

T-SQL
1
2
3
4
5
6
7
8
SELECT
 Код_заказчика, Дата_поставки, Количество, Стоимость_единицы_продукции, a.[Стоимость заказа],  
 b.b.[ПДВ 20%], a.[Стоимость заказа] + b.[ПДВ 20%] AS 'К оплате'
FROM
 Узлы INNER JOIN
 Заказчик ON Узлы.Код_узда = Заказчик.Код_узла cross apply
 (select [Количество]*[Стоимость_единицы_продукции]) a([Стоимость заказа]) cross apply
 (select 0.2 * a.[Стоимость заказа]) b([ПДВ 20%]);



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

15.05.2021, 17:39

Помогаю со студенческими работами здесь

Ошибка недопустимое имя столбца
Привет. Не совсем понимаю, почему sql сервер выдает данную ошибку, можете помочь с решением данной…

Недопустимое имя столбца (Подчеркнутый текст)
Я новичек, Подскажите, запросы нормально работают, а почему имена полей подчеркнуты?

Недопустимое имя объекта
Привет всем. Вот делаю базу данных. Не буду сейчас полностью все здесь пихать. Приведу пример…

Недопустимое имя объекта
Выбивает ошибку: Сообщение 208, уровень 16, состояние 6, процедура Model_GetModels, строка 1…

Недопустимое имя объекта
Добрый день!

У меня такой вопрос, я создал таблицу STUDENT и пытаюсь сделать свой первый запрос …

Недопустимое имя объекта
С помощью запроса создала таблицу:
USE dlvr
CREATE TABLE Поставщики (КодПоставщика int PRIMARY…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

4

Если вы используете SSMS (бесплатную SQL-Server Management Studio), чтобы создать оператор INSERT INTO, щелкнув правой кнопкой мыши нужную таблицу, выберите таблицу сценария как, выберите INSERT To в новом окне запроса, которое мы получим (используя таблицу с именем Customers) .

INSERT INTO [dbo].[Customer]
           ([FirstName]
           ,[LastName]
           ,[Address]
           ,[City]
           ,[State]
           ,[ZipCode]
           ,[AccountNumber]
           ,[JoinDate])
     VALUES
           (<FirstName, nvarchar(max),>
           ,<LastName, nvarchar(max),>
           ,<Address, nvarchar(max),>
           ,<City, nvarchar(max),>
           ,<State, nvarchar(max),>
           ,<ZipCode, nvarchar(max),>
           ,<AccountNumber, nvarchar(max),>
           ,<JoinDate, datetime2(7),>)

Теперь измените раздел VALUES, используя DECLARE для каждого значения.

DECLARE @FirstName nvarchar(max)
DECLARE @LastName nvarchar(max)
DECLARE @Address nvarchar(max)
DECLARE @City nvarchar(max)
DECLARE @State nvarchar(max)
DECLARE @ZipCode nvarchar(max)

INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) VALUES (@FirstName,@LastName,@Address,@City,@State,@ZipCode)

Затем создайте класс, а не помещайте операции с данными в Program.cs с методом, специфичным для добавления новой записи (в следующем примере по-прежнему используется таблица Customers).

Полный исходный код, откуда взят следующий код.

  • Альтернативой cmd.Parameters.AddWithValue является cmd.Parameters.Add, которая обеспечивает точную настройку типа параметра.

  • Альтернативой получению нового первичного ключа, если это необходимо, является добавление точки с запятой в конец INSERT INTO и добавление SELECT CAST(scope_identity() AS int); затем используйте Convert.ToInt32(cmd.ExecuteScalar()) для получения нового ключа. Поэтому после тестирования с помощью SSMS просто вставьте запрос в строковую переменную, и если это не сработает, произойдет что-то еще.

    public bool AddCustomer(string FirstName, string LastName, string Address, string City, string State, string ZipCode, ref int NewPrimaryKeyValue) { bool success = false;

     using (var cn = new SqlConnection { ConnectionString = ConnectionString })
     {
         using (var cmd = new SqlCommand { Connection = cn })
         {
             cmd.CommandText = 
                 "INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) " + 
                 "VALUES (@FirstName,@LastName,@Address,@City,@State,@ZipCode)";
    
             try
             {
                 cmd.Parameters.AddWithValue("@FirstName", FirstName);
                 cmd.Parameters.AddWithValue("@LastName", LastName);
                 cmd.Parameters.AddWithValue("@Address", Address);
                 cmd.Parameters.AddWithValue("@City", City);
                 cmd.Parameters.AddWithValue("@State", State);
                 cmd.Parameters.AddWithValue("@ZipCode", ZipCode);
    
                 cn.Open();
    
                 int result = cmd.ExecuteNonQuery();
    
                 if (result == 1)
                 {
                     cmd.CommandText = "Select @@Identity";
                     NewPrimaryKeyValue = Convert.ToInt32(cmd.ExecuteScalar());
                     success = true;
                 }
             }
             catch (Exception ex)
             {
                 HasErrors = true;
                 ExceptionMessage = ex.Message;
                 NewPrimaryKeyValue = -1;
                 success = false;
             }
         }
     }
    
     return success;
    

    }

вызов вышеуказанного метода.

Вы также можете проверить имена столбцов, используя следующее (все еще сохраняя таблицу клиентов)

SELECT ORDINAL_POSITION, 
       COLUMN_NAME, 
       DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer'
      AND TABLE_SCHEMA = 'dbo';

Полученные результаты

1,id,int
2,FirstName,nvarchar
3,LastName,nvarchar
4,Address,nvarchar
5,City,nvarchar
6,State,nvarchar
7,ZipCode,nvarchar
8,AccountNumber,nvarchar
9,JoinDate,datetime2

Изменить

Другой вариант — создать класс, который представляет данные для вставки, например.

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string AccountNumber { get; set; }
    public DateTime? JoinDate { get; set; }

}

Затем здесь мы используем переданные значения. Обратите внимание, что в этой версии cmd.Parameters.AddWithValue заменяется на cmd.Parameters.Add, а запрос на получение нового первичного ключа добавляется после INSERT INTO, разделенных точкой с запятой.

Чтобы вызвать создание экземпляра класса Customer, заполните свойства и вызовите метод.

public bool AddCustomer(Customer customer)
{
    bool success = false;

    using (var cn = new SqlConnection { ConnectionString = ConnectionString })
    {
        using (var cmd = new SqlCommand { Connection = cn })
        {
            cmd.CommandText =
                "INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) " + // insert
                "VALUES (@FirstName,@LastName,@Address,@City,@State,@ZipCode);" +             // insert
                "SELECT CAST(scope_identity() AS int);";                                      // get new primary key

            try
            {
                cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar))
                    .Value = customer.FirstName;
                
                cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar))
                    .Value = customer.LastName;
                
                cmd.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar))
                    .Value = customer.Address;
                
                cmd.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar))
                    .Value = customer.City;
                
                cmd.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar))
                    .Value = customer.State;
                
                cmd.Parameters.Add(new SqlParameter("@ZipCode", SqlDbType.NVarChar))
                    .Value = customer.ZipCode;

                cn.Open();

                customer.Id = Convert.ToInt32(cmd.ExecuteScalar());
                success = true;

            }
            catch (Exception ex)
            {
                HasErrors = true;
                ExceptionMessage = ex.Message;
                customer.Id = -1;
                success = false;
            }
        }
    }

    return success;
}

person
Karen Payne
  
schedule
24.01.2021

Понравилась статья? Поделить с друзьями:
  • Ошибка не удалось запустить wrye bash
  • Ошибка недостаточно памяти world of warcraft
  • Ошибка недопустимый дескриптор устройства
  • Ошибка не удалось запустить rdr2 exe
  • Ошибка недостаточно оперативной памяти для распаковки архивов