简体   繁体   中英

Concatenate values from SQL and bind to Datatable

Hope you can help...

I have two SQL tables, one has users and the other has user locations that I need to combine into a C# datatable.

The basic query to join them isn't the issue, the problem is that a user may appear in the locations table more than once. In this case I need to pass each location to one row rather than list the user multiple times with multiple locations.

It is part of an ADO.NET proximity search so the current query stands as...

                DECLARE @lat float
                DECLARE @lon float
                SET @lat = @varLat
                SET @lon = @varLon
                DECLARE @point geography = geography::Point(@lat, @lon, 4326);
                DECLARE @distance float
                SET @distance = @varDistance
                SELECT t1.locationId, t1.city, t2.[firstName]+' '+[lastName] as name
                FROM _Locations t1 INNER JOIN _Users t2 ON t2.userId = t1.userId
                WHERE @point.STDistance(centerPoint) <= @distance

I feel like LINQ may help but it's not something I have used before.

There is really not enough information to give you correct answer. It could be done either in sql or in code. That is the T-SQL way.

SELECT u.ID, u.Name, 
stuff(
(select ', ' + ul.ID from UserLocations where ul.UserID = u.ID for xml path('')), 
1, 2, null) locs 
    FROM Users u

UPD:

SELECT t2.[firstName]+' '+[lastName] as name,
       STUFF(
            (SELECT t1.locationId, t1.city FROM _Locations t1 
              WHERE t1.userId = t2.userId 
               AND @point.STDistance(centerPoint) <= @distance FOR XML PATH('')), 
            1, 2, NULL) locs
FROM _Users t2 

Final working query is...

 SELECT t2.[firstName]+' '+[lastName] as name,
        STUFF(
                (
                  SELECT ', ' + t1.city FROM _Locations t1 
                  WHERE t1.userId = t2.userId
                  AND @point.STDistance(centerPoint) <= @distance FOR XML PATH(''), type
                 ).value('.', 'varchar(max)'), 1, 1, ''
              )
          FROM _Users t2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM