Column name as a variable in a database trigger

I am trying to code a pre-insert database trigger to format all varchar2 columns entered into the triggering table. I am using a cursor to get all the relevant column names from all_tab_columns, but do not know how to refer to these values in combination with the ":new" construct within my code. The example below is a very simplified version of what I am trying to do ( it obviously will not work as it is):
declare
cursor column_cur is
select column_name cn
from all_tab_columns
where table_name = 'TEMP_ASSESSMENT'
and data_type = 'VARCHAR2';
v_columnname varchar2(30);
begin
for column_rec in column_cur loop
v_columnname := column_rec.cn;
:new.v_columnname := upper(:new.v_columnname); declare
cursor column_cur is
select column_name cn
from all_tab_columns
where table_name = 'TABLE_X'
and data_type = 'VARCHAR2';
v_columnname varchar2(30);
begin
for column_rec in column_cur loop
v_columnname := column_rec.cn;
:new.v_columnname := upper(:new.v_columnname);
end loop;
end;

Seems to me like the problem in this thread:
http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:59412348055
C.

Similar Messages

  • Having a column name as a variable within a query,Problem!!!!

    I have a problem with a simple query shown below
    SELECT * FROM DisneyWHERE Upper(COLNAME) LIKE UPPER('%' || SEARCHSTRING || '%');SELECT * FROM Disney
    WHERE Upper(COLNAME) LIKE UPPER('%' || SEARCHSTRING || '%');
    My problem, The colname variable is not being recognised as a column name for example
    A user can select to view a set of characters from the DB by username, movies, etc etc (they select this from a combobox) They then enter a search string(textbox)
    colname = username
    Searchstring = pluto
    SELECT * FROM Disney
    WHERE Upper(COLNAME) LIKE UPPER('%' || SEARCHSTRING || '%');
    The problem is orac;e does not seem to be picking up that colname is a column name and seems to be doing a simple comparison. To make this clearer
    it' seems to be trying to match username = pluto
    rather than finding pluto in the username column.
    Has anyone got any ideas how i can get around this. I have a strange feeling it is something to do with dynamic pl/sql but i am new to oracle so i have no idea how to write dynamic queries. Any help would be muchly appreciated
    I am using oracle 11g and visual studio .net 2005

    user10372910 wrote:
    If you can refer me to any material you think i would find helpful to read or experiment with pls let me knowThe online documentation is a good place to look...
    http://www.oracle.com/pls/db102/homepage?remark=tahiti
    Start with the concepts guide which gives a good background to the Oracle database.
    Look up "bind variables", "hard parsing"/"soft parsing" of queries
    In light of what boneist highlighted, you may also want to do a search for "function based indexes".
    Those topics should give you some insight into the performance issues around queries and why it is better to write SQL that uses bind variables and get's soft parsed (re-usable SQL) rather than writing dynamic queries that become hard parsed (non-reusable SQL).

  • Column name as a variable !!!!!!!!!!!!!!!!!!!!

    hi All,
    please I would like to write a query such that the column names is to be variables.
    "select &C1, &C2 from T1 ;" it's working in sql developer but it's not working on apex region.
    thanks a lot.

    Actually, the ADF Faces demo site from Oracle looks (potentially) really cool. I have no idea how it works in the background though so it could be a nightmare. I'd appreciate it if you would post back here once you've given it a try. I'd be genuinely interested to know what it's like to work with.
    Its a bit funny because APEX seems to be coming on leaps and bounds but Oracle don't advertise it much (probably because it's free). That could well be a view that is tainted by being an active member of the community though so it would be intriguing to see what people 'from the outside, looking in' feel about it. You got many people there that have opinions about APEX? The java boys at the place I'm contracting at seem to look down on us with disdain!
    Cheers
    Ben

  • PL/SQL column names in cursor variable

    Hi,
    I try to put all column names of a table in a cursor variable?? without the values, just the column names.
    Can somebody help me, because I really don't know how to do this.
    Thanks,
    Moni

    Hi Jes,
    my table looks like this: T1
    columnNames: id | col1 | col2 | col3 | col4 | col5
    Values: a | b | c| d| e| f
    the number of the columns depend on a how many rows in another table (T2) are entered. If a new row is entered in T2, I have to add a column in table T1.
    and then I have to look what is the new row, compare it with all my existing columnnames in T1 and add the right one.
    my vector should look like this:
    c1:
    id
    col1
    col2
    col3
    col4
    col5
    I hope you know what I mean, it is not very easy to describe!
    Thanks for helping me!
    Moni

  • Variable and column name

    Hi all,
    In an interface, I've got a column which has the same name as a variable.
    When I execute it in ODI 10g all is fine.
    With ODI 11g, it replace the column name by the variable one. If the variable has no value, I've got an SQLException.
    I believe it comes from the colon.
    In the execution code, I have
    INSERT ... VALUES PROJECT.NAME instead of NAME.
    I assume that ODI interprets the NAME with the variable name instead of the column name.
    Has anyone experienced it ?
    Thanks.

    Hi,
    I just tried to reproduce your issue, I didn't experience the case where ODI takes variable name instead of column name. ODI should be able to differentiate between column name and variable name with '#' Symbol prefixed to it. Any name prefixed with #, ODI thinks thats a variable and, it need to be declared in a package.
    In your case, looks like issue is not with the NAME, its with variable having no value. May be that ODI 10g has a default value. However, if a variable has no value, its definitely going to fail the process.
    Regards,
    K

  • Column name in a query contains special characters

    Hi folks,
    The column name in a query contains special characters. For example ~ or ^. The creator of the table put these column names under double quotation while creating the table. When I get the column names form the result set meta data object it returns without quotation. Is there any way to tell the jdbc driver so that it return those column names as it was created, I mean in double quotation.
    The help is urgent. I will appreciate any suggestions. Thanks �.
    [using oracle driver for 10g]
    Thanks
    Angelina

    Just because the column names were in quotations when the database was created doesn't mean that the quotes are actually part of the names. What's inside the quotes is what makes the column name in the database. If I created a column as "abcd" and put it in quotes just like that ("abcd"), it would go in the database as abcd since SQL would strip off the quotes.
    And there's your answer. Just put all column names in quotes whenever you need to talk to SQL. It will strip off the quotes and understand.
    I think SQL will also accept square brackets ([ and ]).

  • How to concatenate column name in PL/SQL

    Here is ex.
    I want to execute like this
    for i in 1 .. 18 loop
    EXECUTE IMMEDIATE 'select qty_sz'||i||' from table1';
    end loop;
    I mean Can I cancatenate column name with a variable?
    your advice is gretly Appeciated.
    Ram.

    It would be a lot easier to diagnose your problem if you posted the error message. Oracle has an awful lot of error messages.
    I thing I have noticed is this:
    EXECUTE IMMEDIATE mysql into var1 using 'qty_sz'||i ;
    You have an implicit datatype conversion there, i being a number and you can only concatenate varchar variables. There is a little wrinkle in this, in that to_char seems to put a space in front of any number. So try this:
    EXECUTE IMMEDIATE mysql into var1 using 'qty_sz'||ltrim(to_char(i));
    and see if it makes any difference.
    Another problem will be if your columns are like this: qty_sz01, qty_sz02,...qty_sz8. because the default mask doesn't incude the leading zero so in that case you should specify the mask in the to_char(i, '09')
    If neither of those fixes your problem post the your error message.
    rgds, APC

  • Special Column names in SQL Server

    Hi,
    I am trying to use ODI to load data from SQL Server to Oracle. My problem is having special column names in the old SQL Server database. The columns have names such as 9500Column1. I tried enclosing the names with square barckets in the model definition but it did not work.
    Any ideas? Any modifications I might make to the LKM?
    Nimrod

    Try enclosing the special fields in double quotes instead of [ and ]. Yes, that isn't the T-SQL standard, but it works, even in SS Studio.
    I had a SELECT statement in a Procedure that died when it hit a space in the column name. After hours of unsuccessful attempts to escape [ and ] it occurred to me that maybe " and " would do the trick as that is the PL/SQL standard. I think the proverbial feather could have knocked me over. Or was that me kicking my self in the rear?
    Regards,
    Cameron Lackpour

  • Could the Database Trigger get a forms variable value

    Hi All
    We have an ERP which connect all users of the system with a single schema (Database user name), We create a record for each user in the ERP itself to specify the privillages for each user
    I would like to make a database trigger to Audit a table , by storing the user name, action (Insert,delete,update) on an audit table.
    The problem is the user name i want to store is not the schema name, but it's stored in a database table and read in a global variable.
    Can i get the user name (which stored in the global variable) in the database trigger ???
    Thanks
    Mostafa Abolaynain

    If this global variable lives inside Forms (which the title of your post seems to indicate), then no.
    A database trigger can only reference "stuff" that lives inside the database session at the database server, not "stuff" that lives inside the proces at the client device.
    You should ask your ERP vendor: there might very well be something (eg. a variable inside a database package) that you can use.

  • Saving result from sp_executesql into a variable and using dynamic column name - getting error "Error converting data type varchar to numeric"

    Im getting an error when running a procedure that includes this code.
    I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql
    DECLARE @retval AS DECIMAL(12,2)
    DECLARE @MonthVal VARCHAR(20), @SpreadKeyVal INT
    DECLARE @sqlcmd AS NVARCHAR(150)
    DECLARE @paramdef NVARCHAR(150)
    SET @MonthVal = 'Month' + CAST(@MonthNumber AS VARCHAR(2) );
    SET @SpreadKeyVal = @SpreadKey; --CAST(@SpreadKey AS VARCHAR(10) );
    SET @sqlcmd = N' SELECT @retvalout = @MonthVal FROM dbo.CourseSpread WHERE CourseSpreadId = @SpreadKeyVal';
    SET @paramdef = N'@MonthVal VARCHAR(20), @SpreadKeyVal INT, @retvalout DECIMAL(12,2) OUTPUT'
    --default
    SET @retval = 0.0;
    EXECUTE sys.sp_executesql @sqlcmd,@paramdef, @MonthVal = 'Month4',@SpreadKeyVal = 1, @retvalout = @retval OUTPUT;
    SELECT @retval
    DECLARE @return_value DECIMAL(12,2)
    EXEC @return_value = [dbo].[GetSpreadValueByMonthNumber]
    @SpreadKey = 1,
    @MonthNumber = 4
    SELECT 'Return Value' = @return_value
    Msg 8114, Level 16, State 5, Line 1
    Error converting data type varchar to numeric.

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql <<
    This is so very, very wrong! A column is an attribute of an entity. The idea that you are so screwed up that you have no idea if you want
    the shoe size, the phone number or something else at run time of this entity. 
    In Software Engineering we have a principle called cohesion that says a model should do one and only one task, have one and only one entry point, and one and only one exit point. 
    Hey, on a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, your mindset is that level of sillyity and absurdity. 
    Do you know that SQL is a declarative language? This family of languages does not use local variables! 
    Now think about “month_val” and what it means. A month is a temporal unit of measurement, so this is as silly as saying “liter_val” in your code. Why did you use “sp_” on a procedure? It has special meaning in T-SQL.  
    Think about how silly this is: 
     SET @month_val = 'Month' + CAST(@month_nbr AS VARCHAR(2));
    We do not do display formatting in a query. This is a violation of at the tiered architecture principle. We have a presentation layer. But more than that, the INTERVAL temporal data type is a {year-month} and never just a month. This is fundamental. 
    We need to see the DDL so we can re-write this mess. Want to fix it or not?
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Passing column names in as a variable

    I know in SQL server there is a way you can pass a variable in to the procedure and put that variable as a column name, Oracle doesn't seem to pick the variable up as a column name. Can anyone show me how with a simple select statement

    bgulcu wrote:
    I'm having a similar problem. I didn't want to open up another thread since it's related.
    Problem:
    I have 107 columns on a table. The number of columns increases almost every month.
    I have an array of columns, which I have gathered from the db. I need to pivot the whole table, but due to indefinite number of columns, it had to be dynamic sql.
    Premature Solution:
    Right now, the solution that we have runs through the array of columns and uses dynamic sql to query for every single cell to get the value. Considering that we have 1000+ rows on this table, in order to do the transformation, we send 107000+ queries which is just ugly. It works, but I don't feel comfortable about it.
    Solution:
    Since we are able to get a single row of 107 columns, why don't we gather the whole row, and get the information out from it instead of tiring up the server? The indefinite number of columns is a problem, but we have the whole list in an array, lets say feature_array. So what I want to do is to get the date from the row, ie myRow.feature_array(1), myRow.feature_array(2), ..., myRow.feature_array(i).
    I just learned that it's not possible to do it (from this thread).You just misunderstood the contents of this thread. What we said is that you can't do such things with static SQL, so you need to use dynamic sql.
    What has also been told was that using dynamic sql for such a purpose is just the result of a bad design. Use a relational table as a bi-dimensional array is not right, it is possible but it's not right for the simple reason that you need a procedural language to process the dynamic SQL that is needed to retrieve data.
    Probably on database programming there's only a rule of thumb and it says: "Maximize SQL minimize PL/SQL" (or any procedural language like java). The only exceptions to keep code in procedural language must depend on a complexity reduction determined by its use. In your case there is no complexity reduction determined by the use of a procedural language.
    In the thread on this link(Schema integrity I discussed about how to implement a solution you can use as alternative for submitting queries with variable column names.
    If you introduce parameter management in your model probably you could have your problem solved with the use of only a single SQL statement. And that may be a good designed model.
    Bye Alessandro

  • Script task to read the column names dynamically and create a table in database based on excel column structure

    Hello,
    Can anyone help me out to write a vb.net script.
    I need to read the column names from excel and based on that column names I need to create a table in database(I have more than one sheet in excel).
    For each sheet columns will be changing and should create a table dynamically for each sheet.
    Any help would be appreciated.

    Refer the below script to read columns in each sheet.
    Dim excelfile As String = Dts.Variables("ExcelPath").Value.ToString
    Dim connectionstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" +
    "Data Source=" + excelfile + ";Extended Properties=Excel 8.0"
    Dim oledbcon As New OleDb.OleDbConnection(connectionstring)
    oledbcon.Open()
    Dim dt As DataTable
    Dim schemaTable As DataTable
    Dim OLEDBCMD As New OleDb.OleDbCommand
    Dim oledbdatareader As OleDb.OleDbDataReader
    Dim columns As String = ""
    dt = oledbcon.GetSchema("Tables")
    Dim TABCOMMAND(20) As String
    Dim TABCOUNT As Integer = 0
    For Each row As DataRow In dt.Rows
    TABCOMMAND(TABCOUNT) = "SELECT * FROM [" & row.Item("TABLE_NAME").ToString & "]"
    OLEDBCMD.CommandText = TABCOMMAND(TABCOUNT)
    OLEDBCMD.Connection = oledbcon
    oledbdatareader = OLEDBCMD.ExecuteReader(CommandBehavior.KeyInfo)
    schemaTable = oledbdatareader.GetSchemaTable()
    For Each myfield As DataRow In schemaTable.Rows
    For Each myproperty As DataColumn In schemaTable.Columns
    If myproperty.ColumnName = "ColumnName" Then
    columns = columns & myfield(myproperty).ToString & ","
    MsgBox(myfield(myproperty).ToString)
    End If
    Next
    Next
    oledbdatareader.Close()
    OLEDBCMD.Dispose()
    Next
    oledbcon.Close()
    Regards, RSingh

  • Can I use bind variable instaed of writing static COLUMN Name

    Hi , I am having a table containing id and column names, the data is stored against that id in other tables. Now I wish to update data into another table so that it goes into apppropriate column without using decode function.
    I am trying to do this:
    EXECUTE IMMEDIATE 'update TEST set :1 = :2
    where PROJECT_ID= :3 and UNIQUE_ID= :4' using P_DEST_COLUMN, P_TEXT_VALUE, P_PROJ_ID, P_TASK_UID;
    the values P_DEST_COLUMN, P_TEXT_VALUE, P_PROJ_ID, P_TASK_UID are populated using a cursor in PL/SQl
    Is this statement valid? If not can you tell me how to do it as I am getting some error I am unable to comprehend.
    thanks
    Rishabh

    Column names cannot be substituted at run-time as bind variables. If you need to specify the column name at run-time, you'd need to construct a new string and execute that string dynamically, i.e.
    EXECUTE IMMEDIATE 'UPDATE test SET ' || p_dest_column || ' = :1 ' || ...From a data model standpoint, storing column names as data elements in another table is generally a rather poor idea. It's likely to make ad-hoc reporting nearly impossible and to cause a lot more parsing than would otherwise be required.
    Justin

  • Why do I get a class conflict between the Prepare SQL.vi and the Get Column Name.vi with the SQL Toolkit compatibility vis from the Database Connectivity Toolkit?

    I have done extensive programming with the SQL Toolkit with LabVIEW versions through 6.1. My customer now wants to upgrade to Windows 7, so I am trying to upgrade to LabVIEW 2009 (my latest purchased version) using the Database Connectivity Toolkit, and the SQL Toolkit Compatibility vis. Everything seemed to be going okay with the higher level SQL operations, but I ran into trouble with the Get Column Name.vi. 
    The pictures below show the problem. The original SQL Toolkit connected the Prepare SQL.vi with the Get Column Name.vi with a cluster of two references, one for connection, and one for sql. The new compatibility vis have a class conflict in the wire because the Prepare SQL.vi contains a cluster with connection, and command references, but the Get Column Name.vi expects a cluster with connection and recordset references. 
    How do I resolve this conflict?
    Thank You.
    Dan

    I've never worked with the old version of the toolkit, so I don't know how it did things, but looking inside the SQL prep VI, it only generates a command, and the the column name VI wants a recordset. I'm not super familiar with all the internals of ADO, but my understanding is that is standard - you only have the columns after you execute the command and get the recordset back. What you can apparently do here is insert the Execute Prepared SQL VI in the middle and that will return what you need.
    I'm not sure why it worked before. Maybe the execute was hidden inside the prep VI or maybe you can get the column names out of the command object before execution. In general, I would recommend considering switching to the newer VIs.
    Try to take over the world!

  • Searching for missing column names in a single database.

    I have a database with about 100 tables, database gets generated using entity framework. The application has been enhanced  so users deployed with older version of the application need to upgrade to newer version. The database generated is both versions
    is same name.
    Now, the older version is missing some tables and column names that are in new database.
    Is there a script that can search for missing fields in a single database as described in this situation?
    Below is my script. Basically, nameofdatabase would the database generated and that already existing. If you install the application and database already exits no new database will be created.
    SELECT * FROM (Select TABLE_CATALOG, Table_name,COLUMN_NAME FROM nameofdatabase.INFORMATION_SCHEMA.COLUMNS) a FULL OUTER JOIN (SELECT TABLE_CATALOG, Table_name,COLUMN_NAME FROM nameofdatabase.INFORMATION_SCHEMA.COLUMNS) b ON b.COLUMN_NAME=a.COLUMN_NAME and
    a.TABLE_NAME=b.TABLE_NAME WHERE b.COLUMN_NAME is null or a.COLUMN_NAME is null ;

    There is a great tool called SQLCompare provide by www.red-gate.com
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

Maybe you are looking for

  • SAFARI crashed after installing Yosemite-HELP!!

    I have macbook air 11 inch bought 2 months ago. Everything was working well until I decided to upgrade to Yosemite- The download took forever so I went to sleep and opened the laptop today. Safari was not opening some websites (msn.com or yahoo.com)

  • How to capture the IP address of the client Machine.

    HI... I want to capture the ip address of the client machine and store it in a field. My client wants to capture the ip address so that he can easily trace out from which client system particular work is done. if there any pre defined function or syn

  • How to serialize only 10 variables in a program among more than 10 variable

    actually i'am new to this forum . any body help me how to serialize only 10 variables in a program among more than 10 variables. assume that there are more than 10 variacles. give me some guidelines

  • Adding BBM contact with old 8703e phone

    I have been trying to add a contact who has an 8703e blackberry but the add won't work.  They can see and accept my invitation but it just comes into my HUB as a notification, saying I can accept it after installing BBM.  Of course, I have BBM alread

  • IBook in Spanish

    I bought an iBook and it came in Spanish, not English. What to do?