Help with dynamic sequel. Return only Distinct Name.

This is simple but how can I return only distinct login name.  Just want to return one set of values.
Please see the desire output and the rule below.  I am using SQL2012.
Thank you for your help in advance.
USE Tempdb;
go
DROP TABLE [dbo].[UserRoleTest];
GO
CREATE TABLE [dbo].[UserRoleTest]
 [LoginId] [varchar](35) NULL,
 [UserName] [varchar](35) NULL,
 [DBRole] [varchar](35) NULL
) ON [PRIMARY]
GO
INSERT INTO dbo.UserRoleTest([LoginId],[UserName],[DBRole])
  VALUES ('[MyDomain\Peter]', 'MyDomain\Peter', '[db_datareader]' ) ;
INSERT INTO dbo.UserRoleTest([LoginId],[UserName],[DBRole])
  VALUES ('[MyDomain\Peter]', 'MyDomain\Peter', '[db_datawriter]' ) ;
INSERT INTO dbo.UserRoleTest([LoginId],[UserName],[DBRole])
  VALUES ('[Home\John]', 'Home\John', '[db_datareader]' ) ;
INSERT INTO dbo.UserRoleTest([LoginId],[UserName],[DBRole])
  VALUES ('User1', 'User1', '[db_datareader]' ) ;
INSERT INTO dbo.UserRoleTest ([LoginId],[UserName],[DBRole])
  VALUES ('User1', 'User1', '[db_datawriter]' ) ;
SELECT *
  FROM [dbo].[UserRoleTest]
go
USE Tempdb;
go
IF OBJECT_ID('dbo.usp_test', 'p') IS NOT NULL
  DROP PROCedure dbo.usp_test
GO
CREATE PROCedure dbo.usp_test
AS
SET NOCOUNT ON;
DECLARE @SQLStr      VARCHAR(8000)
       ,@iCounterId  INT
       ,@LoginId     VARCHAR(35)
       ,@UserName    VARCHAR(35)
       ,@DBRole      VARCHAR(35)
       ,@DBName      VARCHAR(40)
       ,@crlf        CHAR(1) = CHAR(13) + CHAR(10) -- carriage return, new line.
SET @DBName = 'Tempdb'    
--ALTER USER and ALTER ROLE.
DECLARE @t TABLE
  iCounterId   INT  IDENTITY(1,1)  NOT NULL PRIMARY KEY NONCLUSTERED
 ,LoginId      VARCHAR(35)             NULL
 ,UserName     VARCHAR(35)             NULL
 ,DBRole       VARCHAR(35)             NULL
 INSERT @t (LoginId, UserName, DBRole)
 SELECT LoginId, UserName, DBRole
   FROM dbo.UserRoleTest
  --WHERE (DBName = @DBName);
--SELECT * FROM @t
SET @iCounterId = ( SELECT MIN(iCounterId)
                      FROM @t );
   WHILE ( @iCounterId IS NOT NULL )
     BEGIN
       IF ( @iCounterId IS NULL )
         BEGIN
           PRINT 'Exit'
           BREAK
         END
       -- Pick 2 variables.
       SELECT @LoginId = LoginId
             ,@UserName = UserName
             ,@DBRole = DBRole
         FROM @t
        WHERE (iCounterId = @iCounterId )
        --SQL Statement
        --PRINT 'LoginId: ' + @LoginId
        --PRINT 'UserName: ' + @UserName
        --PRINT 'DBRole: ' + @DBRole
         -- This section create users if users do not exist.
         SET @SQLStr = 'USE [' + RTRIM(@DBName) + '];' + @crlf
         SET @SQLStr = @SQLStr + 'IF NOT EXISTS ( SELECT 1 FROM sys.sysusers WHERE [name] = ''' + RTRIM(@UserName) + ''' )' + CHAR(13) +
                          '  BEGIN' +  @crlf + '    CREATE USER ' + @LoginId + ' FOR LOGIN
' + @LoginId + ' WITH DEFAULT_SCHEMA = [' + @UserName + '];' + @crlf +
                          '    ALTER ROLE ' + RTRIM(@DBRole) + ' ADD MEMBER ' + RTRIM(@LoginId) + ';'
+ @crlf + '  END;' + CHAR(13) +
                          'ELSE ' + CHAR(13) + '  BEGIN' + @crlf + '    ALTER USER ' + RTRIM(@LoginId) 
+ ' WITH LOGIN = ' + RTRIM(@LoginId) + ';' + CHAR(13) +
                          '    ALTER ROLE ' + RTRIM(@DBRole) + ' ADD MEMBER ' + RTRIM(@LoginId) + ';'
+ @crlf + '  END;' + @crlf
         PRINT @SQLStr
      SET @iCounterId = ( SELECT MIN(iCounterId)
                            FROM @t
                           WHERE iCounterId > @iCounterId )
   END
GO
EXECute dbo.usp_test
-- Result want:
-- Just return 1 set like below.  Thank you so much.
USE [Tempdb];
IF NOT EXISTS ( SELECT 1 FROM sys.sysusers WHERE [name] = 'MyDomain\Peter' )
 BEGIN
   CREATE USER [MyDomain\Peter] FOR LOGIN [MyDomain\Peter] WITH DEFAULT_SCHEMA = [MyDomain\Peter];
   ALTER ROLE [db_datareader] ADD MEMBER [MyDomain\Peter];
   ALTER ROLE [db_datawriter] ADD MEMBER [MyDomain\Peter];
 END;
 ELSE
  BEGIN
     ALTER USER [MyDomain\Peter] WITH LOGIN = [MyDomain\Peter];
    ALTER ROLE [db_datareader] ADD MEMBER [MyDomain\Peter];
    ALTER ROLE [db_datawriter] ADD MEMBER [MyDomain\Peter];
 END;

Here is an improved version of Prashath's script:
* I use FOR XML PATH which is guaranteed to work to concatenation. The method that Prashanth uses does not have a defined behaviour.
* I'm using quotename through out to delimit all names.
* I did not like that that some names in the table were brackted, but I found a way to neutralise that with parsename. (But that would fail if there is an unquoted name with a dot in it.)
* I introduced the variables @nl and @to make formatting cleaner.
DECLARE @sql nvarchar(MAX) = N'',
        @nl char(2) = char(13) + char(10)
DECLARE @go char(6) = @nl + 'go' + @nl
;WITH cte(UserName, LoginId, DBRole, rn) AS (
   SELECT parsename(UserName, 1), parsename(LoginId, 1), parsename(DBRole, 1),
          ROW_NUMBER() OVER(PARTITION BY UserName, LoginId ORDER BY UserName, LoginId)
   FROM dbo.[UserRoleTest]
SELECT @sql =
   (SELECT CASE WHEN rn = 1 THEN N'IF user_id(' + quotename(UserName, '''') + ') IS NULL ' + @nl +
                    '    CREATE USER '  + quotename(LoginId) + ' FOR LOGIN ' + quotename(LoginId) +
                    ' WITH DEFAULT_SCHEMA = ' + quotename(UserName)
                ELSE 'ALTER USER ' + quotename(LoginId)  + ' WITH LOGIN = ' + quotename(LoginId)
           END  + @go +
           'ALTER ROLE ' + quotename(DBRole) + ' ADD MEMBER ' + quotename(LoginId) + @go
     FROM cte
     ORDER BY rn
     FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)')
PRINT @sql;
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • Help with dynamic statement returning values into collection

    Hi All
    I am trying to use dynamic statement to return values into a collection using the returning clause. However, I get an ORA-00933 error. Here is a simple setup:
    create table t(
        pk number,
        id_batch varchar2(30),
        date_created date,
        constraint t_pk primary key ( pk )
    create or replace type num_ntt is table of number;
    create or replace type vc2_ntt is table of varchar2(30);
    create or replace
    package pkg
    as
      type rec is record(
          pk        num_ntt,    
          id_batch  vc2_ntt
      procedure p(
          p_count in number,
          p_rt    out nocopy rec
    end pkg;
    create or replace
    package body pkg
    as
      procedure p(
          p_count in number,
          p_rt    out nocopy rec
      is
      begin
          execute immediate '
          insert into t
          select level, ''x'' || level, sysdate
          from   dual
          connect by level <= :p_count
          returning pk, id_batch into :pk, :id_batch'
          using p_count returning bulk collect into p_rt.pk, p_rt.id_batch;
      end p;
    end pkg;
    declare
      r  pkg.rec;
    begin
      pkg.p( 5, r );
    end;
    /

    sanjeevchauhan wrote:
    but I am working with dynamic statement and returning multiple fields into a collection.And using an INSERT...SELECT statement combined with a RETURNING INTO clause still does not work. Whether it's dynamic SQL or not: it doesn't work. The link describes a workaround.
    By the way, I don't see why you are using dynamic SQL here. Static SQL will do just fine. And so you can literally copy Adrian's setup.
    Regards,
    Rob.

  • Help with dynamic creation of class object names

    Hi all
    Wonder if you can help. I have a class player.java. I want to be able to create objects from this class depending on a int counter variable.
    So, for example,
    int counter = 1;
    Player p+counter = new Player ("Sam","Smith");the counter increments by 1 each time the method this sits within is called. The syntax for Player name creation is incorrect. What I am looking to create is Player p1, Player p2, Player p3.... depending on value of i.
    Basically I think this is just a question of syntax, but I can't quite get there.
    Please help if you can.
    Thanks.
    Sam

    here is the method:
    //add member
      public void addMember() {
        String output,firstName,secondName,address1,address2,phoneNumberAsString;
        long phoneNumber;
        boolean isMember=true;
        this.memberCounter++;
        Player temp;
        //create HashMap
        HashMap memberList = new HashMap();
        output="Squash Court Booking System \n";
        output=output+"Enter Details \n\n";
        firstName=askUser("Enter First Name: ");
        secondName=askUser("Enter Second Name: ");
        address1=askUser("Enter Street Name and Number: ");
        address2=askUser("Enter Town: ");
        phoneNumberAsString=askUser("Enter Phone Number: ");
        phoneNumber=Long.parseLong(phoneNumberAsString);
        Player p = new Player(firstName,secondName,address1,address2,phoneNumber,isMember);
        //place member into HashMap
        memberList.put(new Integer(memberCounter),p);
        //JOptionPane.showMessageDialog(null,"Membercounter="+memberCounter,"Test",JOptionPane.INFORMATION_MESSAGE);
        //create iterator
        Iterator members = memberList.values().iterator();
        //create output
        output="";
        while(members.hasNext()) {
          temp = (Player)members.next();
          output=output + temp.getFirstName() + " ";
          output=output + temp.getSecondName() + "\n";
          output=output + temp.getAddress1() + "\n";
          output=output + temp.getAddress2() + "\n";
          output= output + temp.getPhoneNumber() + "\n";
          output= output + temp.getIsMember();
        //display message
        JOptionPane.showMessageDialog(null,output,"Member Listings",JOptionPane.INFORMATION_MESSAGE);
      }//end addMemberOn running this, no matter how many details are input, the HashMap only gives me the first one back....
    Any ideas?
    Sam

  • Is it possible to make a search help with dynamic  selection table?

    Hi Experts,
    Is it possible to create search helps with dynamic seletion tables means
    i dont know the selection table names at the time of creation of search help.
    These tables will be determined at runtime.
    if yes, Please give an idea how to create and pass the table names at runtime.
    Thanks
    Yogesh Gupta

    Hi Yogesh,
    Create and fill your itab and show it with FM F4IF_INT_TABLE_VALUE_REQUEST
      CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
        EXPORTING
          retfield        = 'field to return from itab'
          dynpprog        = sy-repid
          dynpnr          = sy-dynnr
          dynprofield     = 'field on your screen to be filled'
          stepl           = sy-stepl
          window_title    = 'some text'
          value_org       = 'S'
        TABLES
          value_tab       = itab
        EXCEPTIONS
          parameter_error = 1
          no_values_found = 2
          OTHERS          = 3.
    Darley

  • Need help with Dynamic Excel File Name please.

    I am try to output an excel file with dynamic date. 
    Here what I done.
    I am using SQL 2012.
    Create Execute SQL Task Connect Type: Excel
    Create Data Flow Task set to DelayValidation: True
    Create OLE DB Sourc
    Create Data Converstion
    Excel Destination
    Excel Connection, Expression, select ExcelFilePath
    @[User::sXLFilePath] +  @[User::sFileName] + RIGHT("0" + (DT_WSTR, 2) DATEPART("DD", GETDATE()), 2)+ RIGHT("0" + (DT_WSTR, 2) DATEPART("MM", GETDATE()), 2) + RIGHT((DT_WSTR,
    4) DATEPART("YYYY", GETDATE()), 2) +".csv"
    C:\ExcelOutPut\SOX_CAM_SQL_Report_010215.xls
    What I try to accomplish is output the file with each day append to it, date must be DDMMYY.
    I google it and found many samples, tested it, and none of them is work for me. 
    Any suggestions or some examples to share is greatly appreciate. 
    I am new to SSIS.  I found one poster have similar issue and inside the posted below, there was one suggestion to create variable and connection string but how do I bind that variable to Excel Connection manger.
    Please help.
    Thank you so much in advance.
    Ex: SOX_CAM_SQL_Report _020215.csv
           SOX_CAM_SQL_Report _030215.csv
    --Similar issue:
    https://social.msdn.microsoft.com/Forums/en-US/bda433aa-c8f8-47c9-9e56-efd20b8354ac/creating-a-dynamic-excel-file?forum=sqlintegrationservices
    Suggestion in the above posted but where can bind this to Excel Connection Manger. 
    Please help provide step by step.  Thanks.
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\temp\\" + "ExcelTarget" + (DT_WSTR,4)DATEPART("yyyy",GETDATE())  +
    ".xls" + ";Extended Properties=\"EXCEL 8.0;HDR=YES\";"
    And yes, as you were intimating, the delay validation on the dataflow should be set.

    Hi NguyenBL,
    According to your description, you created ssis package to export data from database to excel, when the package runs, you want to create new excel and name the file with time stamp. If that is the case, we can achieve the goal by following steps:
    Create a script task used to create excel files.
    Create a data flow task to export data from database to excel.
    Add OLE DB source to data flow task.
    Add Excel Destination to data flow task.
    Create connection manager for OLE DB and Excel.
    Click Excel Connection Manager, in Properties window, click (…) button next to Expressions, then set ExcelFilePath with expression like below:
    "C:\\ETL Lab\\CreateNewExcel\\ExportData_"+REPLACE((DT_STR, 20, 1252)(DT_DBTIMESTAMP)@[System::StartTime], ":", "")+".xls"
    For detail information, please refer to the document:
    https://sqljourney.wordpress.com/2013/01/12/ssis-create-new-excel-file-dynamically-to-export-data/
    If you have any more questions, please feel free to ask.
    Thanks,
    Wendy Fu
    Wendy Fu
    TechNet Community Support

  • Help with dynamic playlist for mpd

    Hi guys,
    I use mpd with sonata for playing my music, and after trying exaile there is one thing id really like for mpd, and that is the dynamic playlist function.
    When you're playing a song in exaile with dynamic playlist enabled, it queries audioscrobbler and automatically adds similar artists/songs to your playlist (if you have them on your pc).
    I dont want to use exaile as it just feels too big and slow and bloated (not KISS ), i know a little bit of python so i thought i'll try and make my own little script/program as Sonata has audioscrobbler support, but i dont think there is anyway to query similar artists.
    I think im going to try and make this as a daemon type program that will run in the background adding songs to the playlist.
    Ive found the code from the exaile source (audioscrobbler.py) which queries lastfm e.g.
    >>> lips = AudioScrobblerQuery(artist='The Flaming Lips')
    >>> for artist in lips.similar():
    ... print artist.name, artist.mbid
    This will print a list of similar artists to the flaming lips.
    I've not done much with python so i thought this would be a good way to try and improve.
    Does anyone have any suggestions as to what the best way to go about searching and comparing the results to my mpd database, would the best way just to be to search the mpd.db?
    And if anyone else has any ideas/comments id like to hear them.
    Edit:
    I just found this too, so i may only need to change some things to integrate it with mpd rather than amarok
    http://www.kde-apps.org/content/show.php?content=31920
    Thanks
    Last edited by Kane (2008-06-05 13:24:33)

    well i just modified the patch into a little script, it does what i need
    its here if anyone wants it
    import audioscrobbler
    import mpd
    import random
    import time
    lastsong = {}
    def timer_control():
    get_similar()
    time.sleep(10)
    timer_control()
    def get_similar():
    audioscrobbler
    client = mpd.MPDClient()
    client.connect("localhost", 6600)
    mpdstatus = client.status()
    prevsonginfo = client.currentsong()
    global lastsong
    if mpdstatus['state'] == "stop": return
    if prevsonginfo == lastsong: return
    lastsong = prevsonginfo
    similarartists = ""
    song = prevsonginfo
    #if not song: break #No song, do nothing
    prevartist = song['artist']
    # Is the info already cached?
    similar_cache = {}
    if similar_cache.has_key(prevartist):
    similarartists = similar_cache[prevartist]
    else:
    #Not cached so fetch from Audioscrobbler
    try:
    similarartists = [artist.name for artist in audioscrobbler.AudioScrobblerQuery(artist=prevartist).similar()]
    # Cache search results and save some time next search
    similar_cache[prevartist] = similarartists
    except audioscrobbler.AudioScrobblerError:
    similar_cache[prevartist] = None # Empty cache
    return # Do nothing!
    if not similarartists: return # Empty list
    # Split list in half and sort upper half
    # this means good matches will have priority
    # but makes sure artist A does not always result in artist B
    half_idx = len(similarartists)/2
    upperhalf = similarartists[:half_idx]
    lowerhalf = similarartists[half_idx:]
    random.shuffle(upperhalf)
    artistlist = upperhalf
    artistlist.extend(lowerhalf)
    # Try each artist in order
    for artist in artistlist:
    try:
    print "Trying:",artist
    songs = client.search("artist", artist)
    if not songs: continue
    selected_song = random.sample(songs, 1)[0]
    client.add(selected_song['file'])
    print "Added", selected_song['title'],"by",selected_song['artist']
    # Delete old song from playlist?
    break
    except mpd.MPDError, e:
    print "MPDError", e.message
    continue
    except ValueError, e:
    print "ValueError:",e.message
    continue
    timer_control()
    Last edited by Kane (2008-06-06 16:22:49)

  • Help With Dynamic PL/SQL LOV Syntax

    Hello
    I am trying to create a dynamic pl/sql lov in Oracle Apex 3.2 on 11g. I am having some issues with the syntax of the statements below and I'd appreciate any suggestions.
    DECLARE
    BEGIN
    IF :p3_current_a_workshop != 0 THEN
    RETURN
    'select distinct workshop_title ||':  '  || presenter_name ||'    $'|| workshop_fee display_value, workshop_id return_value
    from WORKSHOP
    where session_time = 'A'
    and workshop_status = 'Open'
    or workshop_id = :p3_current_a_workshop
    order by 1';
    ELSE
    RETURN
    'select distinct workshop_title ||':  '  || presenter_name ||'    $'|| workshop_fee display_value, workshop_id return_value
    from WORKSHOP
    where session_time = 'A'
    and workshop_status = 'Open'
    order by 1';
    END IF;
    EXCEPTION
            WHEN OTHERS THEN
                HTP.PRN('ERROR'||SQLERRM);         
    END;I am trying to model the above code off of the example given by apex:
    A function that returns a SQL query with two columns:
    IF :MY_ITEM='10' THEN
      RETURN
      'SELECT ename, empno
    FROM  emp
    WHERE depno = 10
    ORDER BY 1';
    ELSE
      RETURN
      'SELECT ename, empno
    FROM emp
    WHERE depno = :my_item
    ORDER BY 1';
    END IF;~Andrew Schultz

    Hi Andrew,
    Try something like:
    DECLARE
    BEGIN
    IF :p3_current_a_workshop != 0 THEN
    RETURN
    ' select distinct workshop_title ||'':  ''  || presenter_name ||''    $''|| workshop_fee display_value, workshop_id return_value '||
    ' from WORKSHOP '||
    ' where session_time = ''A'' '||
    ' and workshop_status = ''Open'' '||
    ' or workshop_id = :p3_current_a_workshop '||
    ' order by 1 ';
    ELSE
    RETURN
    ' select distinct workshop_title ||'':  ''  || presenter_name ||''    $''|| workshop_fee display_value, workshop_id return_value '||
    ' from WORKSHOP '||
    ' where session_time = ''A'' '||
    ' and workshop_status = ''Open'' '||
    ' order by 1 ';
    END IF;
    EXCEPTION
            WHEN OTHERS THEN
                HTP.PRN('ERROR'||SQLERRM);         
    END;Regards,
    Lev

  • Help with dynamic text and and css !

    My second question of the day.
    I'm trying to build a feature in my app in which the user can
    hide/reveal
    bolding and or
    italics and or
    underlining. The text is being loaded in from an xml file
    and I was thinking about styling it with css in order to get the
    underlining. My problem is that the only way I can think about
    pulling this off is to have a css style sheet that has a defined
    bold,italic and underline class defined- - then another one that
    just has a italic and underline class defined -- then another one
    that has just a bold and underline class defined . . . and so on
    and so on. You can see why I would prefer a much more streamlined
    system. Unfortunately my experience with dynamic text styling is
    somewhat limited. Hopefully someone can help me out here.

    Perfect. I knew it was some little snippet that I was
    forgetting. I made a temporary fix of creating a 0% alpha box over
    the button like a fake click area above the text, and that worked
    but I know that it was a half-arsed way of working around it.
    Thanks.

  • Help with dynamic SQL

    Hello,
    I have the following function that works ok:
    CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
    RETURN VARCHAR2 IS
    cursor c is select A.partition_name from (select table_name, partition_name,
    extractvalue (
    dbms_xmlgen.
    getxmltype (
    'select high_value from all_tab_partitions where table_name='''
    || table_name
    || ''' and table_owner = '''
    || table_owner
    || ''' and partition_name = '''
    || partition_name
    || ''''),
    '//text()') import_value from all_tab_partitions) A where table_name = sTable and A.import_value = iImportIndex;
    sPartitionName VARCHAR(20);
    err_num NUMBER;
    BEGIN
    open c;
    fetch c into sPartitionName;
    IF c%ISOPEN THEN
    CLOSE c;
    END IF;
    RETURN sPartitionName;
    EXCEPTION
    WHEN OTHERS THEN
    err_num := SQLCODE;
    --save error in log table
    LOG.SAVELINE(SQLCODE, SQLERRM);
    END Get_Partition_Name;
    I am trying to replace the cursor statement with dynamic SQL, something like (see below) but it doesn't work any more; I think I am missing some quotes.
    CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
    RETURN VARCHAR2 IS
    TYPE t1 IS REF CURSOR;
    c t1;
    sSql VARCHAR2(500);
    sPartitionName VARCHAR(20);
    err_num NUMBER;
    BEGIN
    sSql := 'select A.partition_name from (select table_name, partition_name,
    extractvalue (
    dbms_xmlgen.
    getxmltype (
    ''select high_value from all_tab_partitions where table_name=''''
    || table_name
    || '''' and table_owner = ''''
    || table_owner
    || '''' and partition_name = ''''
    || partition_name
    || ''''''),
    ''//text()'') import_value from all_tab_partitions) A where table_name = :a and A.import_value = :b';
    OPEN c FOR sSql USING sTable, iImportIndex;
    fetch c into sPartitionName;
    IF c%ISOPEN THEN
    CLOSE c;
    END IF;
    RETURN sPartitionName;
    EXCEPTION
    WHEN OTHERS THEN
    err_num := SQLCODE;
    --save error in log table
    LOG.SAVELINE(SQLCODE, SQLERRM);
    END Get_Partition_Name;
    Please advise,
    Regards,
    M.R.

    Assuming the requirement is to find the partition in the supplied table with the supplied high value and the issue is that dba/all_tab_partitions.high_value is a long, one alternative along the same lines as you've done already is as follows. (I've just used a cursor rather than a function for simplicity of demo).
    SQL> var r refcursor
    SQL> set autoprint on
    SQL> declare
      2   ctx dbms_xmlgen.ctxhandle;
      3   v_table_name VARCHAR2(40) := 'LOGMNR_USER$';
      4   v_value      NUMBER       := 100;
      5  begin
      6   ctx := DBMS_XMLGEN.NEWCONTEXT
      7          ('select table_name
      8            ,      partition_name
      9            ,      high_value  hi_val
    10            from   dba_tab_partitions
    11            where  table_name     = :table_name');
    12   dbms_xmlgen.setbindvalue(ctx,'TABLE_NAME',v_table_name);
    13   open:r for
    14   with x as
    15   (select xmltype(dbms_xmlgen.getxml(ctx)) myxml
    16    from   dual)
    17   select extractvalue(x.object_value,'/ROW/TABLE_NAME') table_name
    18   ,      extractvalue(x.object_value,'/ROW/PARTITION_NAME') partition_name
    19   ,      extractvalue(x.object_value,'/ROW/HI_VAL') hi_val
    20   from   x
    21   ,      TABLE(XMLSEQUENCE(EXTRACT(x.myxml,'/ROWSET/ROW'))) x
    22   where  extractvalue(x.object_value,'/ROW/HI_VAL') = v_value;
    23  end;
    24  /
    PL/SQL procedure successfully completed.
    TABLE_NAME
    PARTITION_NAME
    HI_VAL
    LOGMNR_USER$
    P_LESSTHAN100
    100
    SQL> I'm sure there are other ways as well. Especially with XML functionality, there's normally many ways to skin a cat.

  • Help with dynamic page layouts

    Hello JSP Gurus,
    I'm attempting to dynamically generate the page layout for my site based on the organization a user belongs to. Basically, I'd have certain resources like navigation links, graphics, etc, that are modular. Then I'd like to construct the layout using these "moduls" in a dynamic fashion. Does anyone have any suggestions on techniques or technologies that would be useful? I'm not really looking at the portal/portlet model. Is this something that Cocoon could do by storing the layout for each customer as an XML file or something? Any ideas, suggestions, experiences would be helpful.
    Thanks!

    How does Tiles differ from the JetSpeed apache
    project? They both appear to be portal-like
    frameworks, or am I incorrect about that? Which is
    preferred?Frankly, I can't give you an in-depth answer to that. Maybe someone else can help with more details.
    What I can tell you is that JetSpeed seems to be more of a real portal architecture. Emphasis is placed on the framework portion, interfacing with exisiting applications. Visual layout takes second seat to this.
    Tiles on the other hand puts more emphasis on visual layout and reuse.
    Just looking at JetSpeed's visual interfacing a little bit makes me really dislike it. You build tables and such inside of a servlet, so there's a tight coupling (or at least, much tighter than with Struts/Tiles) between the presentation and logic. (I'm basing this on a JavaWorld article at
    http://www.javaworld.com/javaworld/jw-07-2001/jw-0727-jetspeed.html )
    Based on your initial question, it would seem to me that tiles is much closer to what you're looking for (and likely easier to just pick up and use).
    Anyway, take all this with a grain of salt; I'm not exactly an expert on JetSpeed. =)

  • URGENT: Help with dynamic borders!

    Hello all -
    I DESPERATLY need help with this! I am using the code from
    kirupa's xml photo gallery with the thumbnails. right now the alpha
    changes on mouseover, fine...but my client is demanding that it
    draw a border instead. I have been at this for about a week and
    have NO idea how to do this...i have looked at things like API's
    and things...but my main issue is that the images and MC's are all
    created on the fly and i dont know how to code in an on mouseover
    draw a border type of function, no idea at all!
    This is my code as it sits now, PLEASE SOMEONE HELP ME!!!
    thank you in advance!

    really could use some help quick here guys

  • Help with Dynamic Code not displaying only ASP Shields???

    Started working with some .asp pages today and it is not showing me the record set in the brackets. Like this {Recordset.Field} Only giving me the little ASP shield. Looks like this. I have search on google and in dreamweave in the pref's thinking something was not turned on. Can any one help this is driving me nuts.
    theDogger

    I have been working with DW since UltraDev days and I have never had this issue. I did a fresh install of Win7 Pro and now I get this instead of the dynamic info in the window. I really do not think that it matters what view you are in. I do not want to se what is generated by the DB I just want to see what is supposed to be re-ferenced by the DB in the WYSIWYG.It should not matter if I am working in the Designer or classic or what I usually work in the Dual Mode
    It is killing me becasue I can't apply style to the shields it won't let me.
    If I run live view I get the proper info. displayed but I should get something like this in the WYSISYG window {rs_innentory.inv-LG-Image} not the damn ASP shield.
    I know that I am missing something simple that a tick box or something....it is driving me crazy!
    theDogger

  • Please help with dynamic form field names in cfloop

    Hi,
    I need to create a form with day, date, month, year and time for 12 months
    Instead of coding them 12 times, I create day,date,month,year and time fileds in my form 1 time and then I use cfloop from="1" to="12" index="i" to loop these form fields 12 times.
    I gave each form field name such as: <input type="text" name="ScheduleDate_# i #" value=" "> this way each of those field will be named differently such as:
    ScheduleDate_1, ScheduleDate_2,ScheduleDate_3, ScheduleTime_1,ScheduleTime_2, etc
    I'm facing problem when this form is submitted, I think the error has something to do with the pound sign (##) when it comes to updating the back end
    I use MS SQL
    It doesn like this:
    <CFLOOP From="1" To="12" index="k">
    <CFIF Len(Trim(Form.MeetYear_#k#)) NEQ 0 AND Len(Trim(Form.MeetTime_#k#)) NEQ 0>
    <cfquery name="CreateSchedule" datasource="#DSN#">
    UPDATE TableSchedule 
    SET SchedDay = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SchedDay_#k##">,SchedMonth =
    <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SchedMonth_#k##">,SchedDate =
    <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SchedDate_#k##">,SchedYear =
    <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SchedYear_#k##">,SchedTime =
    <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.SchedTime_#k##">
    Where SchedId = <cfqueryparam cfsqltype="cf_sql_numeric" value="#k#">  
    </cfquery>
    </CFIF>
    </CFLOOP>
    Can anyone help please?

    You can't nest hash marks. Do this instead:
    SET SchedDay = <cfqueryparam cfsqltype="cf_sql_varchar" value="#form["SchedDay_" & k]#">
    Dave Watts, CTO, Fig Leaf Software
    http://www.figleaf.com/
    http://training.figleaf.com/

  • Help with Dynamic GUI

    I am trying to create a dynamic gui for a program that when given three names, it will make a list of matches ( wrestling ) against each other.. I got it so when you click foward once.. it brings up the specified amount of text fields.. but when i click previous, it does not pack it fully, and the buttonPanel does not go back to the minimal size, and keeps the whole frame long.
    [code="face.java"]import java.awt.*;
    import java.awt.Component.*;
    import java.awt.event.*;
    public class face extends GUIFrame implements WindowListener, ActionListener {
    static TextField[] nameFields;
    List howMany;
    TextArea finish;
    Button forward, back, startOver, print;
    Panel mainPanel, buttonPanel, numberPanel, namePanel, matchesPanel;
    GridBagLayout gbl;
    GridBagConstraints gbc;
    BorderLayout bpl, mpl;
    CardLayout cl;
    Choice numbers;
    public face() {
    super("Wrestling Order");
    gbl = new GridBagLayout();
    gbc = new GridBagConstraints();
    setLayout(gbl);
    mainPanel = new Panel();
    buttonPanel = new Panel();
    bpl = new BorderLayout();
    back = new Button("Previous");
    back.setEnabled(false);
    back.addActionListener(this);
    back.setActionCommand("numOf");
    buttonPanel.setLayout(bpl);
    buttonPanel.add(back, BorderLayout.WEST);
    forward = new Button("Forward");
    forward.addActionListener(this);
    forward.setActionCommand("names");
    buttonPanel.add(forward, BorderLayout.EAST);
    startOver = new Button("Start Over");
    buttonPanel.add(startOver, BorderLayout.SOUTH);
    //mainPanel
    numberPanel = new Panel();
    numbers = new Choice();
    numbers.add("3");
    numbers.add("4");
    numbers.add("5");
    numberPanel.setLayout(bpl);
    numberPanel.add(numbers, BorderLayout.CENTER);
    cl = new CardLayout();
    mainPanel.setLayout(cl);
    mainPanel.add("numbers", numberPanel);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbl.setConstraints(mainPanel, gbc);
    add(mainPanel);
    gbc.gridx = 0;
    gbc.gridy = 5;
    gbl.setConstraints(buttonPanel, gbc);
    add(buttonPanel);
    addWindowListener(this);
    pack();
    setVisible(true);
    public Panel makeNamePanel(int numOfNames) {
    gbl = new GridBagLayout();
    gbc = new GridBagConstraints();
    gbc.gridx = 1;
    gbc.gridy = GridBagConstraints.RELATIVE;
    nameFields = new TextField[numOfNames];
    Panel makePanel = new Panel();
    for (int x=0; x < nameFields.length; x++) {
    nameFields[x] = new TextField(20);
    makePanel.add(nameFields[x]);
    return makePanel;
    public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
    public void windowOpened(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand() == "names") {
    namePanel = makeNamePanel(Integer.parseInt(numbers.getItem(numbers.getSelectedIndex())));
    mainPanel.add("name", namePanel);
    cl.next(mainPanel);
    forward.setActionCommand("final");
    pack();
    back.setEnabled(true);
    if (e.getActionCommand() == "numOf") {
    cl.previous(mainPanel);
    pack();
    forward.setActionCommand("names");
    back.setEnabled(false);
    that is the face.java .. it extends GUIFrame.. which is as follows..
    * GUIFrame
    * An extension of Frame that uses a WindowAdapter to
    * handle the WindowEvents and is centered.
    import java.awt.*;
    import java.awt.event.*;
    public class GUIFrame extends Frame {
      public GUIFrame(String title) {
        super(title);
        setBackground(SystemColor.control);
        addWindowListener(new WindowAdapter() {
          //only need to override the method needed
          public void windowClosing(WindowEvent e) {
            dispose();
            System.exit(0);
      /* Centers the Frame when setVisible(true) is called */
      public void setVisible(boolean visible) {
        if (visible) {
          Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
          setLocation((d.width - getWidth())/2,
                      (d.height - getHeight())/2);
        super.setVisible(visible);
    }If you could help me out.. Thanks..

    Have you tried using some other layouts... GridBagLayout is a complicated thing to figure out... Might be easier to use some nested panels with different layouts... Particularly, look at SpringLayout.

  • Help with dynamic datasource and record selection

                                                                                                                                                                                                                                                                                     <span>Hi, I&#39;m having some difficulty with part of an application I&#39;m trying to build, but here&#39;s some background first.<br /> <br /> I am a student at the University of Maryland, and I&#39;m writing an application for one of the departments here at the university.  It is sort of a front-end for an access database with a lot of extra functionality.  This includes reports.  First of all, the user can change the databse that the application uses, so I store that in an appsetting.  For this reason, I have to tell the report what database to use at runtime rather than using the database expert.  I am building a sort of report wizard in which the user selects certain values, and based upon those values, the SQL statement that the report gets data from changes.  So almost everything about the report&#39;s data is dynamic and will be determined at runtime.  <br /> <br /> So for example if the user chooses an officer report by chapter names, I do this (chapters is a comma delimited string):<br /> <br /><span style="font-weight: bold"> string sel = "SELECT * FROM [Undergrad Leadership] WHERE [Leadership Position] = &#39;" + txtPosition.Text + "&#39; AND [Chapter Name] IN (" + chapters + ");";</span><br /> <br /> The part I am lost on, is how to actually interface with crystal reports.  In the following code, conn is an OleDbConnection to the correct database, rep is the ReportDocument, and view is a CrystalReportsViewer.<br /> <br /><span style="font-weight: bold"> rep.DataSourceConnections[0].SetConnection(conn.DataSource, conn.Database, false); <br /> rep.RecordSelectionFormula = sel;</span><br /><span style="font-weight: bold"> view.ReportSource = rep;</span><br /> <br /> When I try to load the report, I get the following error message:<br /> Error in formula <Record Selection>:  a number, currency amount, boolean, date, time, date-time, or string is expected here.<br /> <br /> Also, assuming this formula gets fixed, how do I actually get fields from this formula and datasource onto my report, since I can&#39;t do it at design time?  Thanks in advance for the help.<br /> <br /> -Jared<br />    </span>

    <p>RCAPI (Report Creation and Modification) calls are only available with Crystal Reports Server RAS SDKs.  This means that using the bundled version of Crystal Reports for Visual Studio will not allow you to place fields onto the report.  A free copy of Crystal Reports Server comes with a registered copy of Crystal Reports Developer.  My guess is that you don&#39;t have either of these products and that you are just using the product that came with Visual Studio.</p><p>All is not lost.  The first question is, do you really need to add the fields at runtime?  In many cases developers just want to have control of the data that gets sent to the report and they are ok with having the same fields display.</p><p>In your code you are changing the datasource which is fine, and you are assigning a Record selection formula which is also fine.  </p><p>The problem with the record selection is that it doesn&#39;t fit the syntax of the Report.  I would suggest printing out the value that you programatically get for the formula and insert it into the Crystal Report Designer.  You will probably get the same error there and gets some  hints as to why it doesn&#39;t work.</p><p>What I would suggest is creating a template report that already has the fields on the report and then change its datasource at runtime and add a RecordSelectionFormula.</p><p>Otherwise you will have to use RAS to be able to add fields at runtime. </p><p>Rob Horne<br /><a href="/blog/10">Rob&#39;s blog - http://diamond.businessobjects.com/blog/10</a></p>

Maybe you are looking for