Ошибка ora 01036

SQL Server 2016 Developer — duplicate (do not use) SQL Server 2016 Enterprise — duplicate (do not use) SQL Server 2016 Enterprise Core — duplicate (do not use) SQL Server 2016 Standard — duplicate (do not use) Еще…Меньше

Проблемы

Предположим, что на экземпляре SQL Server 2016 установлены службы Microsoft SQL Server Analysis Services (SSAS). Если вы используете поставщик ODBC .NET для подключение к базам данных Oracle и запросы к ней, службы SSAS 2016 могут неправильно создавать отфильтрованные запросы SQL. Кроме того, может появиться сообщение об ошибке, подобное следующему:

ORA-01036: неправильное имя переменной или число.

Решение

Это исправление включено в Накопительное обновление 4 для SQL Server 2016 с пакетом обновления 2.

Сведения о сборках SQL Server 2016

Каждая новая сборка для SQL Server 2016 включает в себя все исправления и исправления для системы безопасности, описанные в предыдущей сборке. Мы рекомендуем установить последнюю сборку для SQL server 2016.

Статус

Корпорация Майкрософт подтверждает наличие этой проблемы в своих продуктах, которые перечислены в разделе «Применяется к».

Ссылки

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

В этой статье упомянуты программные продукты независимых производителей. Корпорация Майкрософт не дает никаких гарантий, подразумеваемых и других, о производительности и надежности этих продуктов.

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

Нужна дополнительная помощь?

Нужны дополнительные параметры?

Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.

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

I am trying to use ALTER USER query for Oracle database using OracleCommand in C# in the following code. It creates the query if the values for Username and password are not empty strings. But I get an error "ORA-01036: illegal variable name/number" when ExecuteNonQuery() is executed.

  string updateQuery = "ALTER USER :user IDENTIFIED BY :password";
  connection = new OracleConnection(LoginPage.connectionString);
  connection.Open();                
  OracleCommand cmd = new OracleCommand(updateQuery, connection);
  cmd.Connection = connection;  
  for(int i=0;i<usersList.Count;i++)
        {
            if (!(selectedUsersArray[i].Equals("")) && !passwordArray[i].Equals(""))
            {
                OracleParameter userName = new OracleParameter();
                userName.ParameterName = "user";
                userName.Value = selectedUsersArray[i];

                OracleParameter passwd = new OracleParameter();
                passwd.ParameterName = "password";
                passwd.Value = passwordArray[i];

                cmd.Parameters.Add(userName);
                cmd.Parameters.Add(passwd);

                cmd.Prepare();
                cmd.ExecuteNonQuery();                   


            }
        }

Could you please suggest what is wrong with my implementation?.

Nagaraj S's user avatar

Nagaraj S

13.2k6 gold badges32 silver badges52 bronze badges

asked Jan 27, 2014 at 7:36

jetty's user avatar

The root cause

In Oracle you have three kinds of SQL statements (and additionally there are PL/SQL blocks):

  • Statements in the Data Definiton Language (DDL). These statements modify the structure of the database. They begin usually with the verbs «ALTER» or «CREATE»
  • Statements in the Data Modification Langugage (DML). There statements modify the content inside of tables, leaving the structure of each table unmodified. These statements usually begin with «INSERT», «MERGE» or «DELETE».
  • Statements in what I call «query language» (there seems to be no canonical name for these). This statements start with the verb «SELECT».

Bind variables in Oracle are only allowed in some special places in DML and query statements. You are trying to use bind variables in a places where they are not allowed. Hence the error.

Solution

Build your statement without bind variables. Build the complete query string instead using string concatenation.

If you want to sanitize the input before concatenating the string, use the DBMS_ASSERT package.

Background

Bind variables can only be used when Oracle can build a query plan without knowing the value of the variable. For DDL statements, there is no query plan. Hence bind variables are not allowed.

In DML and query statements, bind variables are only allowed, when they are used inside a tuple (regarding the underlying set theory), i.e. when the value will be compared with the value in a table or when the value will be inserted in a table. They are not allowed to change the structure of the execution plan (e.g. to change the target table or to change the number of comparisons).

Nick Heiner's user avatar

Nick Heiner

118k187 gold badges474 silver badges698 bronze badges

answered Jan 27, 2014 at 8:36

stefan.schwetschke's user avatar

Just for others getting this error and looking for info on it, it is also thrown if you happen to pass a binding parameter and then never use it. I couldn’t really find that stated clearly anywhere but had to prove it through trial and error.

answered Dec 27, 2018 at 21:41

Beatscribe's user avatar

BeatscribeBeatscribe

4238 silver badges17 bronze badges

2

I just spent several days checking parameters because I have to pass 60 to a stored procedure. It turns out that the one of the variable names (which I load into a list and pass to the Oracle Write method I created) had a space in the name at the end. When comparing to the variables in the stored procedure they were the same, but in the editor I used to compare them, I didnt notice the extra space. Drove me crazy for the last 4 days trying everything I could find, and changing even the .net Oracle driver. Just wanted to throw that out here so it can help someone else. We tend to concentrate on the characters and ignore the spaces. . .

answered May 12, 2016 at 19:33

SDanks's user avatar

SDanksSDanks

5851 gold badge6 silver badges18 bronze badges

1

You defined one oracleCommand but used it in ‘for’.
it means you are adding parameter with the same name to one OracleCommand.
you should use cmd.Parameters.clear() to refresh your parameters.

for(int i=0;i<usersList.Count;i++)
        {
            if (!(selectedUsersArray[i].Equals("")) && !passwordArray[i].Equals(""))
            {
                cmd.Parameters.clear();//Add this line
                OracleParameter userName = new OracleParameter();
                userName.ParameterName = "user";
                userName.Value = selectedUsersArray[i];

                OracleParameter passwd = new OracleParameter();
                passwd.ParameterName = "password";
                passwd.Value = passwordArray[i];

                cmd.Parameters.Add(userName);
                cmd.Parameters.Add(passwd);

                cmd.Prepare();
                cmd.ExecuteNonQuery();                   


            }
        } 

Phiter's user avatar

Phiter

14.5k14 gold badges50 silver badges84 bronze badges

answered Mar 30, 2016 at 11:33

Sargol's user avatar

SargolSargol

611 silver badge3 bronze badges

1

The Oracle error ORA-01036 means that the query uses an undefined variable somewhere. From the query we can determine which variables are in use, namely all that start with @. However, if you’re inputting this into an advanced query, it’s important to confirm that all variables have a matching input parameter, including the same case as in the variable name, if your Oracle database is Case Sensitive.

Superdooperhero's user avatar

answered Jan 27, 2014 at 7:39

Ravi Mavani's user avatar

1

This error happens when you are also missing cmd.CommandType = System.Data.CommandType.StoredProcedure;

answered Oct 6, 2016 at 15:55

mpora's user avatar

mporampora

1,3715 gold badges23 silver badges64 bronze badges

 cmd.Parameters.Add(new OracleParameter("GUSERID ", OracleType.VarChar)).Value = userId;

I was having eight parameters and one was with space at the end as shown in the above code for «GUSERID «.Removed the space and everything started working .

answered Sep 25, 2018 at 3:02

Sribin's user avatar

SribinSribin

3054 silver badges16 bronze badges

I was having the same problem in an application that I was maintaining, among all the adjustments to prepare the environment, I also spent almost an hour banging my head with this error «ORA-01036: illegal variable name / number» until I found out that the application connection was pointed to an outdated database, so the application passed two more parameters to the outdated database procedure causing the error.

answered Sep 18, 2019 at 14:12

Genivan's user avatar

GenivanGenivan

1612 gold badges3 silver badges10 bronze badges

You cannot pass user/table name to pl/sql with a parameter. You can create a procedure and build sql and then execute immediately to achieve that.

Superdooperhero's user avatar

answered Jan 27, 2014 at 7:39

hkutluay's user avatar

hkutluayhkutluay

6,7742 gold badges32 silver badges53 bronze badges

I have faced same problem … For the problem is like this, I am calling the PRC inside cpp program and my PRC taking 4 arguments but while calling I used only 1 arguments so this error came for me.

Begin Example_PRC(:1); End; // this cause the problem 
Begin Example_PRC(:1,:2,:3,:4); End; // this is the solution

answered Oct 19, 2020 at 6:49

Mantu's user avatar

MantuMantu

1331 silver badge5 bronze badges

I had the same issue today when using Python module cx_Oracle. In my case, the root cause was an invalid variable name.

Example: SELECT * FROM DATA WHERE KEY IN (:_0, :_1, ...)

When I changed _0 to var0, it worked fine.

From this blog post, I found these rules for variable names:

  • Must start with a letter
  • Maximum size is limited to 30 letters
  • Cannot contain whitespace characters
  • Can contain dollar sign (‘$’), underscore (‘_’) and hash sign (‘#’)
  • Is case-insensitive

answered Apr 26, 2021 at 8:14

kevinarpe's user avatar

kevinarpekevinarpe

20.2k26 gold badges125 silver badges153 bronze badges

I had the same problem, was learning connection to oracledb.
previous code-

SELECTALLCANDIDATES = "Select * from candidate_master";
data= await connection.execute(SELECTALLCANDIDATES, {autoCommit:true})

Removed the {autoCommit:true} and it started working fine.
Correct code-

SELECTALLCANDIDATES = "Select * from candidate_master";
data= await connection.execute(SELECTALLCANDIDATES)

Still don’t know why but it works.

answered May 29, 2022 at 10:56

Sherlock-Holmes-2-2-1's user avatar

Just wanted to add to the points already mentioned by @stefan.schwetschke. At the moment, Oracle does not support executemany() with «select» queries.

Example of a code snippet which gives the error is :

sql = """
    SELECT *
    FROM TABLE1
    WHERE 
        col1 = :cd
"""
data = [{'cd' : 1}, {'cd': 2}, {'cd': 3}]

cur.executemany(sql, data)


    

answered Apr 26 at 15:59

Swathi Venkatesh's user avatar

Check your named variables match, I had the same problem, I had a spelling mistake/typo in one of my parameters

answered Mar 11, 2022 at 13:16

Chuma Madyosi's user avatar

0

I know there are related questions, but most of the resolutions I have come across on the web have the same solution, take the semicolon predecessor off your statement in the where clause. However, this won’t work for me because I don’t have a semicolon.

I am using MyBatis and running NUnit tests.

MyBatisCode

<select id="GetLineNumber" parameterClass="HashTable" resultClass="long">
  <![CDATA[
      SELECT
                     HP.LINE_NUM  
      FROM
                      ODS.HAIL_PLCY_LINE_NUM
      WHERE     
                      PLCY_ID = #PolicyId#
      AND             HCL_ID = #HailCoverageId#
</select>

C# Code:

  Hashtable lineNumberHash = new Hashtable
      {
         {"PolicyId",x.PolicyId}
            ,{"HailCoverageId",x.Id}
                 };
    lastDatabaseCoverage.AddRange(IbatisSqlMapper.QueryForList<T>("GetLineNumber", lineNumberHash));

«X» in the above code is an object and the properties PolicyId and Id are valid so please disregard the bit of contextualless information!

Note that I am used to SQL Server so if the Select, From, Where is off then I apologize for the easy fix.

I keep getting the «ORA01036 illegal variable…» message

This is my first question so I don’t know how fast they get answered, hopefully fairly quickly though :-)

Thanks in advance!

May 1, 2021

I got ” ORA-01036: illegal variable name/number ” error in Oracle database.

ORA-01036: illegal variable name/number

Details of error are as follows.

ORA-01036: illegal variable name/number

Cause: Unable to find bind context on user side

Action: Make sure that the variable being bound is in the SQL statement.



illegal variable name/number

This ORA-01036 errors are related to Unable to find bind context on user side.

Make sure that the variable being bound is in the SQL statement.

Check and fix the bind variable in the code.

Do you want to learn Oracle Database for Beginners, then read the following articles.

Oracle Tutorial | Oracle Database Tutorials for Beginners ( Junior Oracle DBA )

 1,436 views last month,  2 views today

About Mehmet Salih Deveci

I am Founder of SysDBASoft IT and IT Tutorial and Certified Expert about Oracle & SQL Server database, Goldengate, Exadata Machine, Oracle Database Appliance administrator with 10+years experience.I have OCA, OCP, OCE RAC Expert Certificates I have worked 100+ Banking, Insurance, Finance, Telco and etc. clients as a Consultant, Insource or Outsource.I have done 200+ Operations in this clients such as Exadata Installation & PoC & Migration & Upgrade, Oracle & SQL Server Database Upgrade, Oracle RAC Installation, SQL Server AlwaysOn Installation, Database Migration, Disaster Recovery, Backup Restore, Performance Tuning, Periodic Healthchecks.I have done 2000+ Table replication with Goldengate or SQL Server Replication tool for DWH Databases in many clients.If you need Oracle DBA, SQL Server DBA, APPS DBA,  Exadata, Goldengate, EBS Consultancy and Training you can send my email adress [email protected].-                                                                                                                                                                                                                                                 -Oracle DBA, SQL Server DBA, APPS DBA,  Exadata, Goldengate, EBS ve linux Danışmanlık ve Eğitim için  [email protected] a mail atabilirsiniz.

Thanks for the inputs

I tried below code-1 and it’s working fine but it’s running for very long time
code-1:
data=[‘data1′,’data2’]

dsn_tns = cx.makedsn(cred_test[‘HOST’], cred_test[‘PORT’], service_name=cred_test[‘SERVICE_NAME’])
conn = cx.connect(user=cred_test[‘USER’], password=cred_test[‘PASWRD’], dsn=dsn_tns)
cursor = conn.cursor()
for x in data:
cursor.execute(‘INSERT INTO table_name (col_name) values (»+x+»)’)
conn.commit()

when I am using executemany method in code-2.I’ getting DatabaseError: ORA-01036: illegal variable name/number

code-2:
data=[‘data1′,’data2’]

dsn_tns = cx.makedsn(cred_test[‘HOST’], cred_test[‘PORT’], service_name=cred_test[‘SERVICE_NAME’])
conn = cx.connect(user=cred_test[‘USER’], password=cred_test[‘PASWRD’], dsn=dsn_tns)
cursor = conn.cursor()
cursor.prepare(‘INSERT INTO table_name (col_name) values (:0)’)
cursor.executemany(None,data)
conn.commit()

Понравилась статья? Поделить с друзьями:
  • Ошибка ora 01013
  • Ошибка ora 01002
  • Ошибка ora 00980
  • Ошибка ora 00979
  • Ошибка ora 00936 missing expression oracle