Referencial integrity

Hello
I can insert a record into parent table even there is no record in child table.
However,if the child row doesnt exist, I cannot update a parent table.
What is the reason for this and what to do to overcome?
idle> select * from p;
         X
         2
         7
        15
        19
        20
idle> select * from c;
         X
         2
         7
        19
        15
idle> update p set x=21 where x=15;
update p set x=21 where x=15
ERROR at line 1:
ORA-02292: integrity constraint (SYS.SYS_C004407) violated - child record found

The Child Record exists when you are updating the parent table p.
Tip:Always Name your constraints
Here is what you should do
SQL> alter table p drop primary key cascade ;
Table altered.
SQL> alter table p add constraint pk_p$x primary key (x) ;
Table altered.
SQL> alter table c add constraint fk_c$x foreign key (x) references p(x) deferrable;
Table altered.
SQL> alter session set constraint = deferred ;
Session altered.
SQL> update p set x=21 where x=15;
1 row updated.
SQL> update c set x=21 where x=15;
1 row updated.
SQL> select * from p ;
         X
         2
         7
        19
        20
        21
SQL> select * from c;
         X
         2
         7
        21
        19
SQL> alter session set constraint = immediate ;
Session altered.HTH
SS

Similar Messages

  • How to know which table has got referencial integrity constraint

    Dear All,
    How can i know which table has got referencial integrity constraint on which table ?
    Ex : Department id column is a primary key in departments table whereas it is a foreign key in employees table. From where can i find the info regarding the relation between employees and departments table ?
    Waiting for your reply.
    Regards,
    Shyam

    you can use dba_constraints or all_constraints to help.
    http://download.oracle.com/docs/cd/B14117_01/server.101/b10755/statviews_1037.htm
    Example:
    select owner, CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME from dba_constraints where R_OWNER=':A' and R_CONSTRAINT_NAME=':B'
    A = owner of primary key
    B = constraint name (primary key name)

  • Referencial integration check

    Can any explain me what is purpose of Referencial integration check  in the communication structure.

    refrential entry check means verifying the consistency of data coming from various sources.
    Check the below link for more info:
    http://help.sap.com/saphelp_nw04/helpdata/en/3a/14c43bb7137503e10000000a11402f/content.htm
    Regards,
    Kamaljeet Singh
    Message was edited by: Kamaljeet Singh

  • Design issue  - Historical data - referencial integrity

    Hi,
    I dont know if this is the right place to post this question, but
    I would to like know about the design issues in storing historical data .
    I have a historical table about events ( notifications, alarms, etc ).
    In historical table would I store fields with foreign key to the master table ( device table ) ?
    In this design , how handle then updates ( remove record ) to the master table ?
    would I have a trigger to update the historical table too ? Or I mustn' t permit
    updates in master table primary Keys ?
    And about no store The foreign keys in the historical data ?
    What are the disvantages of this model ?
    Thank you,
    Faria

    Faria,
    The answer depends on why you want historical data.
    Is the historical data to be used for auditing or legal purposes?
    Are you trying to move historical data for performance reasons?
    Is there some other purpose?
    If you're doing this for auditing purposes, I don't recommend using foreign keys since you won't easily be able to capture delete activity.
    I mostly use Designer for all of our designs and typically will turn on server side journaling for this purpose. Designer will then generate the journaling tables and write the triggers to manage the whole process. You don't even need to be a programmer to figure it out.
    Let me know back if this isn't your purpose or you need clarification.
    Thanks, George

  • Basic questions on data modeling

    Hi experts,
    I have some basic questions regarding data modeling within MDM. I understand the available table types and the concept of lookup fields. I know that the MDM data modeling concept is different to the relational concept. But having a strong database background my first step was to design a relational data model which I would like to transfer to a MDM repository. Unfortunately I didn't found good information material on this. So here are some questions maybe you can help me:
    1) Is it the right approach to model n:m relationships with multivalued lookup fields? E.g. main table Users with lookup field from subtable SapAccounts (a user can have accounts in different SAP systems, that means more than one account).
    2) Has a record always be unique in MDM repositories (e.g. should we use Auto ID's in every table or do we have to mark a combination of fields as unique)? Is a composite key of 2 or more fields represented with marking these fields as unique?
    3) The concept of relationships in MDM is only based on relationships between single records (not valid for all records in a table)? Is it necessary to define all relationships similar to the relational data model in MDM? Is there something similar to referential integrity in MDM?
    4) Is it possible to change the main table to a sub table later on if we realize that it has also to be used as a lookup table for another table (when extending the data model) or do we have to create a new repository from scratch?
    Thank you for your answers.
    Regards, bd

    Yes you are correct. It is almost difficult to map relational database to mdm one. But again MDM is not 'just' a database. It holds much more 'master' information as compared to any relational db.
    1) Is it the right approach to model n:m relationships with multivalued lookup fields? E.g. main table Users with lookup field from subtable SapAccounts (a user can have accounts in different SAP systems, that means more than one account).
    Yes Here you need to use MV look up tables or can also try Qualifier tables if it gets more complex
    2) Has a record always be unique in MDM repositories (e.g. should we use Auto ID's in every table or do we have to mark a combination of fields as unique)? Is a composite key of 2 or more fields represented with marking these fields as unique?
    Concept of uniqueness differs here that you also have something called Display Fields (DF). A combination of DF can also be treated as Unique one. For instance while importing records if you select these DF as a combination, you will eliminate any possible of duplicates based on this combination. Auto Id is one of the ways to have a unique id once record is within MDM. While you use UF or DF to eliminate any possible duplicates at import level
    3) The concept of relationships in MDM is only based on relationships between single records (not valid for all records in a table)? Is it necessary to define all relationships similar to the relational data model in MDM? Is there something similar to referential integrity in MDM?
    Hmm... good one. Referencial Integrity. What I assume you are talking is that if you have relationships between tables then removing a record will not be possible as it is a foreign key for some record. Here MDM does not allow that. As Relationships within MDM are physical and not conceptual. For instance material can have components. Now if material does not exist then any relationship to components is not worthwile to maintain. Hence relationshsip is eliminated.  While in relational model relationships are more conceptual. Hence with MDM usage of lookups and main table you do not need to maintain these kind of relationships on your own.
    4) Is it possible to change the main table to a sub table later on if we realize that it has also to be used as a lookup table for another table (when extending the data model) or do we have to create a new repository from scratch?
    No. It is not possible to convert main table. There is only one main table and it cannot be changed.
    I went for the same option but it did not work. What I suggest is to look up your legacy system one by one and see what fields in general can be classified as Master, Reference, Transactional - You will start getting answers immediately.

  • Cascade or delete in database server, why if my EJB do it for me??

    Hi,
    I am in design phase of a database for my j2EE application. In the database desing i have some relationships entities, that have foreign keys. I have several options about foreign keys in the relationships, cascade deletes, restrict .... all in my database server.
    But, when i am reading the referencial integrity of the entity EJBs CMP relationships, the entity beans make the cascade deletes automaticaly for maintain the relationsships.
    Need i make my relationships in my database server with cascade delete options or leave it for my application server???
    Another one, if i make relationships in my database server, why i need do it in my entity beans???
    tanks, sorry for my poor english

    Hi Markus,
    Tanks for your answer, if this tip only for entity beans with CMP???
    For example, if i have some entity beans, one with CMP and other with JDO, or for example, an entity beans that use CMP and JDO for access to few tables (i dont know that it is possible or it a good design), how can i design the relationships update/delete cascades in my database server, all entity beans persistence types support his referencial integrity ?? if this if true i think that i forget the relationships updates/deletes cascades in my database server.
    At this moment, i dont know what type of persistence i will use in my application server. I dont undertand yet wath approach i must follow, i design my database and after design my entity beans over this database or i must foget my database and beging with entity beans design first .... i have a big problem, i need read a lot of more.
    Something for help me???
    Very, very thanks

  • Designing XML Application

    (this has been posted to the XML list, but I´m using both Oracle DB and BDB XML, so I'd like to hear a different opnion. Sorry if this is repeated.)
    Hello,
    I'm in the process of designing a relatively large XML DB System and I'm having some doubts regarding the best structure for the main XML document, in order to optimize search as well as organizing the document in such a way that is not relational (as I usually tend to think when designing an XML DB, for background reasons).
    Basically, we're trying to create a single XML document, but there's a lot of information spread in other entities and tables. We´re trying to minimize the tables and aggregate as much information as possible in a single XML file, to avoid any "relational" query, but also without getting redundant. To illustrate what I mean, here is an example:
    <?xml version="1.0" encoding="UTF-8"?>
    <doc>
         <people>
              <person>
                   <name> Johnny </name>
                   <address> St. Street, 444 </address>
              </person>
              <person>
                   <name> Tom </name>
                   <address> Mr. Street, 444 </address>
              </person>
              <person>
                   <name> Cat </name>
                   <address> Dr. Street, 444 </address>
              </person>
         </people>
         <vehicle>
              <driver>
                   <!-- redundant information, like above -->
                   <person>
                        <name> Johnny </name>
                        <address> St. Street, 444 </address>
                   </person>
              </driver>
         </vehicle>
    </doc>As you can see above, we have some redundant information repeated. Also, most importantly, I have no way of having some referencial integrity. Now, in the next example, I have tried adding a reference, using an ID node in the person element, in order to avoid the redundancy and get some integrity:
    <?xml version="1.0" encoding="UTF-8"?>
    <doc>
         <people>
              <person id="10">
                  <name> Johnny </name>
                   <address> St. Street, 444 </address>
              </person>
              <person id="11">
                   <name> Tom </name>
                   <address> Mr. Street, 444 </address>
              </person>
              <person id="12">
                   <name> Cat </name>
                   <address> Dr. Street, 444 </address>
              </person>
         </people>
         <vehicle>
              <driver>
                   <!-- storing just an ID reference> -->
                   <person>
                        <id>10</id>
                   </person>
              </driver>
         </vehicle>
    </doc>But that's my point: am I thinking "relational" here? Is there any other way to solve this, in a more efficient and secure way?
    best regards,
    - Breno

    Hi Breno,
    Why not get rid of the list of people altogether, and simply have vehicles with drivers? Then when you really need the list of people, you can just do a query like this:
    collection()//personOr why not place a vehicle element inside of a person element, and get rid of the list of vehicles? Of course, it might be that you need to model a system where a vehicle has more than one driver, in which case maybe what you already have is better.
    With XML, it's not that the old "relational" way of structuring data is wrong - it's just that there could be a simpler way to do things in certain circumstances - namely exhibiting relationship by containment, rather than by reference.
    John

  • Designing XML Database

    Hello,
    I'm in the process of designing a relatively large XML DB System and I'm having some doubts regarding the best structure for the main XML document, in order to optimize search as well as organizing the document in such a way that is not relational (as I usually tend to think when designing an XML DB, for background reasons).
    Basically, we're trying to create a single XML document, but there's a lot of information spread in other entities and tables. We´re trying to minimize the tables and aggregate as much information as possible in a single XML file, to avoid any "relational" query, but also without getting redundant. To illustrate what I mean, here is an example:
    <?xml version="1.0" encoding="UTF-8"?>
    <doc>
         <people>
              <person>
                   <name> Johnny </name>
                   <address> St. Street, 444 </address>
              </person>
              <person>
                   <name> Tom </name>
                   <address> Mr. Street, 444 </address>
              </person>
              <person>
                   <name> Cat </name>
                   <address> Dr. Street, 444 </address>
              </person>
         </people>
         <vehicle>
              <driver>
                   <!-- redundant information, like above -->
                   <person>
                        <name> Johnny </name>
                        <address> St. Street, 444 </address>
                   </person>
              </driver>
         </vehicle>
    </doc>As you can see above, we have some redundant information repeated. Also, most importantly, I have no way of having some referencial integrity. Now, in the next example, I have tried adding a reference, using an ID node in the person element, in order to avoid the redundancy and get some integrity:
    <?xml version="1.0" encoding="UTF-8"?>
    <doc>
         <people>
              <person id="10">
                  <name> Johnny </name>
                   <address> St. Street, 444 </address>
              </person>
              <person id="11">
                   <name> Tom </name>
                   <address> Mr. Street, 444 </address>
              </person>
              <person id="12">
                   <name> Cat </name>
                   <address> Dr. Street, 444 </address>
              </person>
         </people>
         <vehicle>
              <driver>
                   <!-- storing just an ID reference> -->
                   <person>
                        <id>10</id>
                   </person>
              </driver>
         </vehicle>
    </doc>But that's my point: am I thinking "relational" here? Is there any other way to solve this, in a more efficient and secure way?
    best regards,
    - Breno

    You may like to take a look at HyperJAXB that I have used recently for a structure similar to yours. In HyperJAXB, you use JAXB binding with Hibernate on relational databas. So that you can get the results as XML document but you can also leverage relational database structure. And you can control all that without writing any code by adding annotations to XML schema document.
    -- Deha Peker

  • Transformation Routine

    Hi
    In my customer master data, I have a customer group field attached to each customer along with other fields/ attributes of customer. Now i have data going to a cube through a routine in the transformation, which works fine.
    Now i see a problem. A particular customer number is not getting updated with the customer group field in Cube. All other customers are getting their data. Only this customer is not getting updated with that mandatory field. Earlier, this customer was not assigned a cust group in R/3. Sometime back, they have corrected that, and even in BI customer master data, i see all the fields filled for that customer.
    But its failing to upload into the cube. Any ideas why its failing ? My master data is also activated everyday.
    thx
    venkat

    Hi Venkat,
    Cust Grp is being updated through routine.
    If check the routine, also check how may records exists in the customer master for ther particular customer. do you have any compounded objects for the customer master
    There is a check box in the transformation for referencial integrity check.
    Regards
    Ajay

  • IN Vs Exists

    Hi ,
    Recently I was asked in an interview: When we would "IN" clause would be preferred to use over "EXISTS" clause. I had told the interviewer that "EXISTS" will ignore NULL value if the table has any. Wheter was I correct? Please provide valueable inputs.
    Regards,
    Achyut K

    S10390 wrote:
    Check this Tom's post
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:953229842074
    I think that was on a very old version of oracle (8.1.6). Oracle has changed a lot over the time.
    Here is a simple example.
    I have EMP and DEPT table like this. With relation defined as following
    SQL> select table_name, constraint_name, constraint_type, r_constraint_name
      2    from user_constraints
      3   where table_name in ('EMP', 'DEPT');
    TABLE_NAME                     CONSTRAINT_NAME                C R_CONSTRAINT_NAME
    DEPT                           DEPT_PK                        P
    EMP                            EMP_FK_DEPT_NO                 R DEPT_PK
    EMP                            EMP_PK                         PNow a simple query using IN
    SQL> select * from emp e where e.deptno in (select d.deptno from dept d);
         EMPNO ENAME  JOB              MGR HIREDATE         SAL        COM     DEPTNO
          7369 SMITH  CLERK           7902 02-APR-81       2975          0         20
          7499 ALLEN  SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD   SALESMAN        7698 22-FEB-81       1250        500         30
          7566 JONES  MANAGER         7839 02-APR-81       2975          0         20
          7654 MARTIN SALESMAN        7698 28-SEP-81       1250       1400         30
          7698 BLAKE  MANAGER         7839 01-MAY-81       2850          0         30
          7782 CLARK  MANAGER         7839 09-JUN-81       2450          0         10
          7788 SCOTT  ANALYST         7566 19-APR-87       3000          0         20
          7839 KING   PRESIDENT            17-NOV-81       5000          0         10
          7844 TURNER SALESMAN        7698 08-SEP-81       1500          0         30
          7876 ADAMS  CLERK           7788 23-MAY-87       1100          0         20
    11 rows selected.
    SQL> select * from table(dbms_xplan.display_cursor);
    PLAN_TABLE_OUTPUT
    SQL_ID  f7h123zffyf6y, child number 0
    select * from emp e where e.deptno in (select d.deptno from dept d)
    Plan hash value: 2872589290
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      |       |       |     2 (100)|          |
    |*  1 |  TABLE ACCESS FULL| EMP  |    11 |   418 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter("E"."DEPTNO" IS NOT NULL)
    18 rows selected.The amazing thing is that the DEPT table is not scanned at all. I guess the CBO is using the referencial
    integrity to determine scanning fo EMP table would be sufficient.
    Now using EXISTS
    SQL> select * from emp e where exists (select null from dept d where d.deptno = e.deptno);
         EMPNO ENAME  JOB              MGR HIREDATE         SAL        COM     DEPTNO
          7369 SMITH  CLERK           7902 02-APR-81       2975          0         20
          7499 ALLEN  SALESMAN        7698 20-FEB-81       1600        300         30
          7521 WARD   SALESMAN        7698 22-FEB-81       1250        500         30
          7566 JONES  MANAGER         7839 02-APR-81       2975          0         20
          7654 MARTIN SALESMAN        7698 28-SEP-81       1250       1400         30
          7698 BLAKE  MANAGER         7839 01-MAY-81       2850          0         30
          7782 CLARK  MANAGER         7839 09-JUN-81       2450          0         10
          7788 SCOTT  ANALYST         7566 19-APR-87       3000          0         20
          7839 KING   PRESIDENT            17-NOV-81       5000          0         10
          7844 TURNER SALESMAN        7698 08-SEP-81       1500          0         30
          7876 ADAMS  CLERK           7788 23-MAY-87       1100          0         20
    11 rows selected.
    SQL> select * from table(dbms_xplan.display_cursor);
    PLAN_TABLE_OUTPUT
    SQL_ID  8x38asybd9j0v, child number 0
    select * from emp e where exists (select null from dept d where
    d.deptno = e.deptno)
    Plan hash value: 2610556560
    | Id  | Operation          | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |         |       |       |     3 (100)|          |
    |   1 |  NESTED LOOPS SEMI |         |    11 |   451 |     3   (0)| 00:00:01 |
    |   2 |   TABLE ACCESS FULL| EMP     |    11 |   418 |     2   (0)| 00:00:01 |
    |*  3 |   INDEX UNIQUE SCAN| DEPT_PK |     4 |    12 |     1   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - access("D"."DEPTNO"="E"."DEPTNO")
    21 rows selected.Here the DEPT table is scanned. So as already said it all deptnds. And need to tested for every case.

  • DS 5.0 plugins

    The FAQ mentions that there are plugins for the execution of business rules. Does a plugin of this type exist for download somewhere or is it "build your own solution"?

    iDS 5.0 is shipping with a few plugins (Attribute Uniqueness, Referencial Integrity, 7 bits clean...).
    Otherwise, you can build your own solution by writing your own plugin... However, the plugin API is not supported with iDS 5.0 (it is with iDS 5.1).
    Regards,
    Ludovic.

  • 2 right joins - how to add another right join to this statement?

    Hi all,
    I had to upgrade my sql statement and add another column. my previuos sql was:
              SELECT TR.ID, TA.Name, TR.idTarget, TR.Controller_Status, TR.previuosYear, TR.deduction, TR.idProduction, SUM(CSV.cur_amount) AS Accumulated,    PD.Name AS PName, PD.type_2, CL.ToRange AS growth
              FROM agent AS TA, production_name AS PD, calculation AS CL, target AS TR
              RIGHT JOIN csv_production AS CSV ON CSV.ID=TR.ID AND CSV.Production_Date BETWEEN '2006-10-01' AND '2006-12-31'
              WHERE TA.ID=TR.ID
              AND PD.idProduction = TR.idProduction
              AND CL.idCalculation = ANY (SELECT MIN(idCalculation) FROM calculation GROUP BY idProduction)
              AND TR.idProduction=CL.idProduction
              AND TR.startDate= '2006-10-01' AND TR.endDate='2006-12-31'
              GROUP BY CSV.IDI had to add this line:
    RIGHT JOIN csv_net_production AS CSV_net ON CSV_net.IATA=TR.IATA AND CSV_net.Production_Date BETWEEN '2006-10-01' AND '2006-12-31'  my end result looks like this:
              SELECT TR.ID, TA.Name, TR.idTarget, TR.Controller_Status, TR.previuosYear, TR.deduction, TR.idProduction, SUM(CSV.cur_amount) AS Accumulated,  SUM(CSV_net.cur_amount) AS net_Accumulated, PD.Name AS PName, PD.type_2, CL.ToRange AS growth
              FROM agent AS TA, production_name AS PD, calculation AS CL, target AS TR
              RIGHT JOIN csv_production AS CSV ON CSV.ID=TR.ID AND CSV.Production_Date BETWEEN '2006-10-01' AND '2006-12-31'
                               RIGHT JOIN csv_net_production AS CSV_net ON CSV_net.ID=TR.ID AND CSV_net.Production_Date BETWEEN '2006-10-01' AND '2006-12-31' 
              WHERE TA.ID=TR.ID
              AND PD.idProduction = TR.idProduction
              AND CL.idCalculation = ANY (SELECT MIN(idCalculation) FROM calculation GROUP BY idProduction)
              AND TR.idProduction=CL.idProduction
              AND TR.startDate= '2006-10-01' AND TR.endDate='2006-12-31'
              GROUP BY CSV.IDBUT!!! the accumulated (Accumulated, net_Accumulated,) is multiplied by 3, which means that I must add another WHERE statement (i think?!)
    thanks for any pointers

    how do u relate csv_production ,csv_net_production ?
    the one comparison i viewed is TR.ID against the IDs of these 2 tables
    I mean
    is there any relationship between these 2 tables?
    specifically
    is there any referencial integrity or like constraint exists between these 2 tables?
    if so u can write a where condition csv_production.ID=csv_net_production.ID

  • Error in customer_update FM

    Hi,
    When i am trying to add a new record using the customer_update FM into KNVP table it says system error. Can some one tell me what the error is for ?
    Thanks in advance.

    Hi Subbu,
    Most of these update function modules have a logic of importing and exporting data from and to memory. So unless you did all that this function module is expecting, it will not work, because of issues with referencial integrity and what not.
    The interface of the function module is not the only thing that it expects. So please don't use such function modules in your custom code. Use either one of the ones Rob suggested, or find something that is not a update function module.
    It looks like you are trying to insert a customer partner into the table. You cannot have a partner that is not in KNA1. The partner record has to be created as a customer first and then only you can use that customer as a partner. Never try to insert records into some tables, even if you are using a standard SAP function module. All these update function modules will mostly do inserts in a sequence and nothing else. So if you are using something in the middle and the sequence is broken then your data will not be in sync.
    Srinivas

  • Foreign Keys involving two different databases/schemas

    Hi -- I'm wondering if it's possible to set a foreign key that involves tables that live in different databases/schemas. And, if it is possible, is it a horrible design idea?
    Thanks,
    ~Christine

    cav0227, you have asked two different two part questions.
    1 - Is it possible to set up FK that span owners and is this good design?
    Yes, it is possilbe and there if the data is related then yes it is good design. We like to minimize the number of object owners in our system and use a table naming standard where the first two or three letters of the table name represent a system code: ap, ar, gl for accounts receivable, accounts payable, and general ledger. Other may prefer to have an AP owner, AR owner, and a GL owner.
    Ownership has no direct bearing on quality of design. If the tables are related then you should define the FK no matter who the owner is.
    2 - Is it possible to define FK to remote (distributed) tables and is the good design? The answer is no. FK cannot reference remote objects. To enforce referencial integrity accross databases via the database, rather than in the application, requires the use of table triggers.
    As far as good design that depends on why the data is remote and why the tables need to be linked. There are issues related to availability, recovery, and performance when data is distributed. Having such a relationship could be good design or bad design depending on if all the inter-related factors have been considered.
    IMHO -- Mark D Powell --

  • Create Test data using T-SQl script for each row

    Hi team,
    I am looking for a sql code snippet which read data from below table
    UserId username contact
     1      Anil    111
     2      Sunil   222
    and insert data to below table with some test data appending sequence number 1,2,3 for only City and Email. Both are different tables
    and does not have any referencial integrity
    No of records inserted for user is configurable for example count = 3
    Username  City  Email
    Anil      city1 email1
    Anil      city2 email2
    Anil      city3 email3
    Sunil      city1 email1
    Sunil      city2 email2
    Sunil      city3 email3

    DECLARE @cnt INT=3
    DECLARE @Users TABLE(UserId INT, UserName VARCHAR(99),Contact INT)
    INSERT INTO @Users VALUES
    (1,'Anil',111),
    (2,'Sunil',222)
    SELECT UserName,'city'+CAST(num AS varchar(10)) city FROM @Users
    CROSS APPLY
    SELECT TOP(@cnt) number +1 AS num
                    FROM master..spt_values
                    WHERE type = 'P') AS Der
    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