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).

Similar Messages

  • Error : The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.

    Hi all,
        I have created one SP for sending mail with formatting the HTML code inside script whenever i am individually declaring it and printing its expected but the problem at time of executing SP its giving error like this
    Msg 132, Level 15, State 1, Line 47
    The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
    what is the possibilities to overcome this problem follwing is my stored procedure code 
    ALTER PROCEDURE [dbo].[USP_DataLoadMailsend_essRules]
    AS
    BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    BEGIN TRY
    ---BEGIN TRANSACTION T1
    DECLARE @packagelogid INT
    DECLARE @batchlogid INT
    DECLARE @packagestatus CHAR(2)
    select @batchlogid =19870
    --print(@batchlogid)
    DECLARE @script VARCHAR(MAX)
    DECLARE @tableHTML VARCHAR(MAX)
    DECLARE @mailheader VARCHAR(50)
    DECLARE @count INT
    DECLARE @recipients1 VARCHAR(50)
    DECLARE @subject1 VARCHAR(200)
    DECLARE @sql VARCHAR(MAX)
    Declare @UserId varchar(Max)
    Declare @Information varchar(max)
    Declare @TableHTML1 varchar(max)
    Declare @TableHTML2 varchar(max)
    SET @mailheader = ''
    SET @mailheader = (select case
    WHEN FileUpload = 'F'
    THEN 'BussinessRules is Aborted'
    WHEN (InRule = 'S')
    AND (
    SELECT sum(isnull(ErrorRecords, 0)) tot
    FROM abc.FileUploadSummary z
    WHERE z.BatchId = bts.BatchId
    GROUP BY BatchId
    ) > 0
    THEN 'BussinessRules is Processed with Errors'
    WHEN InRule = 'F'
    THEN 'BussinessRules is Failed'
    WHEN (InRule = 'S')
    AND (
    SELECT sum(isnull(ErrorRecords, 0)) tot
    FROM abc.FileUploadSummary z
    WHERE z.BatchId = bts.BatchId
    GROUP BY BatchId
    ) = 0
    THEN 'BussinessRules is Succeeded'
    end
    from abc..BatchStatus bts where BatchId=@batchlogid)
    /* Selecting Person Mail as Recipient */
    SELECT TOP 1 @recipients1 = EmailId FROM abc.PersonEmail
    WHERE PersonId = ( SELECT TOP 1 personid FROM abc.FileUploadSummary WHERE BatchId = @batchlogid )AND EmailTypeId = 1
    /* Selecting UserId*/
    select top 1 @UserId=loginid from abc.FUS where BatchId=@batchlogid
    /*Selecting Information about the Status */
    Set @Information=
    (select case
    WHEN FileUpload = 'F'
    THEN 'BussinessRules is Aborted'
    WHEN (InRule = 'S')
    AND (
    SELECT sum(isnull(ErrorRecords, 0)) tot
    FROM abc.FileUploadSummary z
    WHERE z.BatchId = bts.BatchId
    GROUP BY BatchId
    ) > 0
    THEN 'BussinessRules is Processed with Errors'
    WHEN InRule = 'F'
    THEN 'BussinessRules is Failed'
    WHEN (InRule = 'S')
    AND (
    SELECT sum(isnull(ErrorRecords, 0)) tot
    FROM abc.FileUploadSummary z
    WHERE z.BatchId = bts.BatchId
    GROUP BY BatchId
    ) = 0
    THEN 'BussinessRules is Succeeded'
    end + N' <br> <B>BatchId= '+ convert(varchar(250),(select @batchlogid)) +'</B>'
    from abc..BatchStatus bts where BatchId=@batchlogid )
    /*Selecting the Error Reason*/
    if exists (select 1 from BatchStatus where BatchId=@batchlogid and ( InRule='f'))
    begin
    set @TableHTML1 = '<table border=1><tr><th>Sr.No.</th><th><P>Error Reason :</th></tr>'+
    cast((select td= ROW_NUMBER()over (order by (select 1)),'',
    td=isnull(e.ErrorDescription, '')
    from abc.x.tbPackageErrorLog e --50594
    join abc.x.tbPackageLog p -- 10223
    on p.PackageLogID=e.PackageLogID
    where p.BatchLogID= @batchlogid FOR XML PATH('tr'), TYPE )
    as NVarchar(max)) +'</table>'
    -- print @tableHTML
    if not exists (select 1 from BatchStatus where BatchId=@batchlogid and ( InRule='f'))
    set @TableHTML2 = 'Error Reason :N/A'
    end
    -- insert into #tmp values ( @TableHTML1)
    --select * from #tmp
    Set @tableHTML= 'Hello '+@UserId+', <br>Information:'+isnull(@Information,'') +
    '<Table Border=1><Tr><th>Sr No</th><th>Uploaded files </th>:'+
    CAST ((select td= ROW_NUMBER()over(order by f.FileUploadId), '',
    td = f.TableName , ''
    from abc.FileUploadSummary F where BatchId=@batchlogid
    FOR XML PATH('tr'), TYPE ) AS NVARCHAR(max) )
    +'</table>'+
    'Error Reason :'+isnull(isnull(@TableHTML1,'')+ isnull(@TableHTML2,''),'N/A')+ --concat (isnull(@TableHTML1,''),isnull(@TableHTML2,'')
    '<br> Please login to Your Account for further Details..!'
    +'<br>@Note: This is system generated message, Do not reply to this mail. <br>Regards,<br>'+
    'Admin'
    print @tableHTML
    SET @sql = ' EXEC msdb.dbo.sp_send_dbmail @profile_name = ''DBA_mail_test''
    ,@recipients = ''' + isnull(@recipients1,'''') + ''',@subject = ''' + isnull(@mailheader,'''') + ''',
    @body = ''' +isnull(@tableHTML,'''')+ ''',
    @body_format = ''HTML'''
    Exec(@sql)
    END TRY
    BEGIN CATCH
    PRINT error_message()
    -- Test whether the transaction is uncommittable.
    -- IF (XACT_STATE()) = - 1
    -- ROLLBACK TRANSACTION --Comment it if SP contains only select statement
    DECLARE @ErrorFromProc VARCHAR(500)
    DECLARE @ErrorMessage VARCHAR(1000)
    DECLARE @SeverityLevel INT
    SELECT @ErrorFromProc = ERROR_PROCEDURE()
    ,@ErrorMessage = ERROR_MESSAGE()
    ,@SeverityLevel = ERROR_SEVERITY()
    --INSERT INTO dbo.ErrorLogForUSP (
    -- ErrorFromProc
    -- ,ErrorMessage
    -- ,SeverityLevel
    -- ,DateTimeStamp
    --VALUES (
    -- @ErrorFromProc
    -- ,@ErrorMessage
    -- ,@SeverityLevel
    -- ,GETDATE()
    END CATCH
    END
    please help me to solve this problem
    Niraj Sevalkar

    This is no string http in your procedure. Then again the error message points to a line 47 outside a stored procedure. I can't tell it is outside, since there is no procedure name.
    But I see that you have this piece of dynamic SQL:
    SET @sql = ' EXEC msdb.dbo.sp_send_dbmail @profile_name = ''DBA_mail_test''
    ,@recipients = ''' + isnull(@recipients1,'''') + ''',@subject = ''' + isnull(@mailheader,'''') + ''',
    @body = ''' +isnull(@tableHTML,'''')+ ''',
    @body_format = ''HTML'''
     Exec(@sql)
    Why is this dynamic SQL at all? Why not just make plain call to sp_send_dbmail?
     EXEC msdb.dbo.sp_send_dbmail @profile_name = 'DBA_mail_test'
    ,@recipients = @recipients1, @subject = @mailheader, @body = @tableHTML
    Erland Sommarskog, SQL Server MVP, [email protected]

  • 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

  • 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.

  • 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

  • Update SAME column name in two tables from ONE query

    Dear All Seniors
    Please tell me is it possible to update a same column name in two tables.
    I have two tables in same schema
    (1)table name
    pem.igp_parent
    column name
    igp_no.
    igp_type
    (2)table name
    pem.igp_child
    column name
    igp_no.
    igp_type
    i want to update igp_no column in one query please tell me how it would be possible.
    thanks
    yassen

    You want to update the data from what to what? Where is the new data coming from?
    If you are trying to put the same data in two different tables, that strongly implies that you have a normalization problem that needs to be addressed.
    Why do you want a single query rather than updating each table in turn? Can you join the two target tables to produce a key-preserved view?
    Justin

  • To Select Data from Mutiple Table having different column name

    Dear All,
    I have 100 tables under one user Operation, each table has column containg the code of the Data Entry Operator, But name of the column in each table is different.
    Can anyone give the script to run from SQL PLUS so the we can find the total entry of each D.E. Operator per month.
    Thanks and Regards,
    Manoj

    Perhaps the UNION ALL operator is what you want.
    SELECT data_entry_operator, count(*) AS qty
    FROM(
    SELECT de_oper AS data_entry_operator FROM a
    UNION ALL
    SELECT d_e_operator FROM b
    UNION ALL
    SELECT d_e_op FROM c
    GROUP BY data_entry_operator;

  • 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

  • Membership rules does not work with UDF column name having the max length

    Found a bug in OIM .
    Membership rules does not work with UDF column name having the maximum length
    Steps to Reproduce
    1.Create a UDF having max column name length for eg UDF_USR_PERSONAL_SUB_DOMAIN_CO (lable = Personal Code)
    2. Create a simple Rule like Personal Code = 7000
    3. Assign this Rule as a member ship rule of a Group.
    4. Create a user with Personal Code = 7000.
    5. User doesnot get the group membership.
    Thanks
    Suren

    Yes , i verified logs as well .
    If you just decrease the column name length , w/o making change to any other attributes , it starts working ..
    Thanks
    Suren

  • 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

  • Changing the column names displayed via an ODBC driver

    Hi we are just starting to used Crystal Reports to improve the reporting capabaility of a legacy application, we can access the data fine using an ODBC driver. What we want to do is change the column names that are displayed within Crystal Reports so they are more user friendly and not in techno speak,, so that the users can create their own reports. Do we need to used Business Objects to setup a Universe to do this, is their a simple cheaper method sorry if this post is in the wrong section

    Can you set up "views" in your database? That would probably be the easiest way to do this.
    -Dell
    - A computer only does what you told it to, not what you thought you told it to!</p>

  • 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

  • HOWTO: Declare a variable within a function.

    I'm having a hard time declaring a variable within a function. This is my code:
    CREATE OR REPLACE FUNCTION schemaName.functionName (inParam VARCHAR2(20))
    RETURN VARCHAR2 IS VARCHAR2(10)
    BEGIN
    DECLARE paramLength NUMBER; --This is not working. The docs do not state what the size of the number returned by LENGTH is.
    SELECT LENGTH(inParam) INTO paramLength FROM DUAL;
    IF paramLength < 10 THEN
    RETURN '';
    ELSE
    /* Clean up the value */
    RETURN inParam
    END IF;
    END;

    In relation to your own code...
    CREATE OR REPLACE FUNCTION schemaName.functionName (inParam VARCHAR2(20)) RETURN VARCHAR2 IS
    paramLength NUMBER;
    BEGIN
      /* Clean up the value */
      paramLength = LENGTH(inParam);
      IF paramLength < 10 THEN
        RETURN NULL;
      ELSE
        RETURN inParam
      END IF;
    END; You don't need to use SQL to determine the length of a string.

  • Invalid column name when executing explain plan

    SQL Developer version 4.0, SQL Worksheet, Windows 2000, Database 9.2.0.6.
    When attempted to run a explain plan on a simple two table join query, it generates error invalid column name. Removed aliases and simplify query to one table row count, and still get the same error. Even tried the schema owner and got the same error.
    I decided to check the explain plan table and found out that it was from an older version. Recreated the explain plan table and was able to run the explain plan.
    I'm just posting this in the event somebody else runs into the same problem.

    This was fixed in the 4.1 or 1215 build. Please update by downloading or check for updates.
    -thanks
    kris

  • Java.sql.SQLException:  Invalid column name: user_id

    Hi,
    I am using SQL Server 2000 database and using a Java DAO class executing an SQL query using preparedStatement.The issue is that intermittently i get the following exception: "SQLException:Invalid column name". I checked the filed name in the table and the filed name i gave in the resultset.getInt("field_name")and both are matching.The parameter values for the query are fetched from a JSP report and the surprsing issue is that this exception comes on & off. So iam unable to find the cause of this exception.Can anyone help me out?
    Query Used :
    SELECT usrs.user_id,uperm.value,uedis.attrib_value.......
    FROM USERS usrs
    LEFT OUTER JOIN extended_user_attributes uedis
    ON (usrs.user_id = uedis.user_id AND usdis.attrib_id=?),
    user_permission uperm
    WHERE usrs.user_id = uperm.user_id
    AND uperm.name=?
    I am getting exception when iterating resultset.
    ResultSet rs = preparedStatement.executeQuery();
    while(rs.next())
    UserID userid = new UserID();
    userid.setUserID(rs.getInt("user_id"));
    Thanks
    Balaji.M

    Giving an alias name to the column name will work. If the query uses join or fetching rows from multiple tables, then giving an alias name to the column name, should work fine.
    By,
    Sethu
    It seems you have two user_id columns and the server
    or driver names the column automatically(I am not
    sure of that) in some way. Try giving some alias to
    the field you want, like:
    SELECT usrs.user_id
    u_user_id,uperm.value,uedis.attrib_value.......
    userid.setUserID(rs.getInt("u_user_id"));HTH
    MikeBy

Maybe you are looking for

  • Ipod classic isn't recongnized in Windows or itunes

    I have an ipod 160gb classic. It was working fine a few weeks ago but after updating to the latest itunes, it's stopped working. It isn't recognized on my computer (I'm running Windows Vista) or in itunes at all. My USB ports and the cables I have be

  • Powerbook 1.67 G4 for Logic?

    Powerbook for Logic? I purchased a 1.67 Powerbook last summer thinking I was going to upgrade my protools 001 to 002. Now M-Audio is offering its Project Mix, and I'm thinking about going that route and trying Logic. I'm concerned that the Logic spec

  • BRconnect Error

    Hi, I am getting BRconnect error with this external pgm Background job... log.................... Job started Step 001 started External command: BRCONNECT Related parameter: -c -u / -f stats -t all -f collect -p 16 Ext. prog.: BR0801I BRCONNECT 7.00

  • Severe corruption of .MOV files in Lightroom & unusable processing speed

    Hi all, I run on an Intel i7 quad core, 12 GB Ram, 2 GB Graphics Card (nvidia), Raid 0, 2x512 GB Harddisk space (1 TB), Windows Vista 64bit using the latest cut of Lightroom 3.4.1 64bit. Using a Canon 7D with latest firmware updates, for RAW/JPG/MOV

  • BW Query - result by latest month

    Dear Expert, I have a query that contains multiple key figures. One of the key figure, need to display result by the latest month and not sum of all month. I have 2 scenario: 1. YTD 10/2012 will display data of october 2012 only instead of sum of all