In database design, in order to reduce the number of records stored in a table, a relationship of 1 pairs can be stored in the same record, for example, one application is used by more than one person, and one storage method is as follows:
This can result in more and more records, and there is a way to store the data in 2 of records:
The advantage of the first method is that it is very convenient to display the employee name, which is associated with the employee Information table; The second method is very cumbersome to display the name of the maintainer, for example, we have the following two tables:
If object_id (' [EMP] ') is not null drop TABLE [EMP]
go
CREATE TABLE [EMP] ([employee ID] varchar (3), [name] varchar (4))
I nsert [emp]
Select ' 001 ', ' John ' union ALL
Select ' 002 ', ' Dick ' union ALL
Select ' 003 ', ' XXX '
if object_id (' [ App] is not a null drop table [app] Go
CREATE TABLE [app] ([application ID] varchar (6), [application name] varchar (5), [Maintenance employee ID] varchar (11)
Insert [app]
select ' APP001 ', ' Apply a ', ' 001,002,003 ' union ALL
Select ' APP002 ', ' Apply B ', ' 002,003 '
The result of the request is that the app table displays the name of the maintenance employee, so the problem can be decomposed and solved step by step. For "001,002,003" if you want to display its name, you can use the following statement:
Select ', ' +e.[name] from emp e
where CHARINDEX (', ' +e.[employee id]+ ', ', ', ' + ' 001,002,003 ' + ', ') >0 for
XML Path (')
The results obtained are as follows
How do you do this if you want to achieve a result for every record in the app table?
SELECT DISTINCT
[application ID],
[application name],
[maintenance employee ID],
stuff (SELECT, ' +e.[name] from emp e
where CHARINDEX (', ' +e.[staff id]+ ', ', ', ' +t. Maintenance employee id+ ', ') >0
for XML Path (')
, 1,1, ') as maintenance employee name from
app T
Final results