>Ti ho postato 2 tabelle semplici,in realta il db è molto + complesso
>ma non posso postarlo ... sorry
>
>Per esempio all'interno della tabella center , ci sono circa
>30 città ....
I dati sono un po' pochini e mi sono limitato a recuperare 2 utenti (tu dovrai modificare la TOP(2) in TOP(50)):
USE tempdb;
CREATE TABLE dbo.center(
id_center int NOT NULL,
city varchar(10) NULL,
CONSTRAINT PK_center PRIMARY KEY(id_center)
);
CREATE TABLE dbo.[user](
id_user int NOT NULL,
id_center int NOT NULL,
name varchar(10) NULL,
surname varchar(10) NULL,
CONSTRAINT PK_user PRIMARY KEY(id_user),
CONSTRAINT FK_user_center FOREIGN KEY(id_center)
REFERENCES dbo.center(id_center)
);
INSERT dbo.center VALUES
(1, 'Milano')
, (2, 'Roma')
, (3, 'Napoli');
INSERT dbo.[user] VALUES
(1, 1, 'paolo', 'rossi')
, (2, 2, 'stefano', 'bianchi')
, (3, 1, 'michele', 'verdi');
GO
CREATE FUNCTION dbo.udf_GetUsers(
@id_center int
)
RETURNS TABLE
RETURN(
SELECT TOP(2) *
FROM dbo.[user]
WHERE id_center = @id_center
);
GO
SELECT U.*, C.city
FROM dbo.center AS C
CROSS APPLY dbo.udf_GetUsers(C.id_center) AS U;
/* Output:
id_user id_center name surname city
----------- ----------- ---------- ---------- ----------
1 1 paolo rossi Milano
3 1 michele verdi Milano
2 2 stefano bianchi Roma
(3 row(s) affected)
*/
DROP FUNCTION dbo.udf_GetUsers;
DROP TABLE dbo.[user], dbo.center;
Ciao!
--
Lorenzo Benaglia
Microsoft MVP - SQL Server
http://blogs.dotnethell.it/lorenzo/
http://italy.mvps.org