Click here to Skip to main content
15,891,725 members
Please Sign up or sign in to vote.
3.60/5 (2 votes)
Problem: I'm filling asp.net report from sql server by applying multiple joins on different tables. It works but creates a problem where am picking PoliceStation name by help of cell no. Problem is that 1 cell no can be of many police stations, so it picks each Policestation name and disply that it in report. I just want 1 police station name which i require from PoliceStations table

Query:

SQL
SELECT [ID]
      ,LEFT(REPLACE(convert(varchar, CmsSMSDb.dbo.SendMessages.SendingDateTime, 113), ' ','/'), 11) + ' ' +
       RIGHT(REPLACE(convert(varchar, CmsSMSDb.dbo.SendMessages.SendingDateTime, 113), ' ','/'), 12)
      as SendingDateTime
      ,[ToMobileNo]
      ,[Message]
      ,Designations.Name as [ToDesignation]
      FROM [CmsSMSDb].[dbo].[SendMessages] 
      inner join 
      CPOCMS.dbo.Designations
      ON CPOCMS.dbo.Designations.MobileNo = CmsSMSDb.dbo.SendMessages.ToMobileNo
      where Convert(date,CmsSMSDb.dbo.SendMessages.SendingDateTime)>= @DateFrom 
      AND 
      Convert(date,CmsSMSDb.dbo.SendMessages.SendingDateTime)<= @DateTo


      Union All

      SELECT [ID]
      ,LEFT(REPLACE(convert(varchar, CmsSMSDb.dbo.SendMessages.SendingDateTime, 113), ' ','/'), 11) + ' ' +
       RIGHT(REPLACE(convert(varchar, CmsSMSDb.dbo.SendMessages.SendingDateTime, 113), ' ','/'), 12)
      as SendingDateTime
      ,[ToMobileNo]
      ,[Message]
      ,'SDpo'+' '+CPOCMS.dbo.PoliceStations.PsName as [ToDesignation]
      From [CmsSMSDb].[dbo].[SendMessages] 
      inner join CPOCMS.dbo.PoliceStations
      ON CPOCMS.dbo.PoliceStations.sDpo_ContactNo = SendMessages.ToMobileNo
      where Convert(date,CmsSMSDb.dbo.SendMessages.SendingDateTime)>= @DateFrom 
      AND 
      Convert(date,CmsSMSDb.dbo.SendMessages.SendingDateTime)<= @DateTo
      order by SendMessages.ID


e.g.

City Police St. | 0900800800
Bill Rd PoliceSt | 0900800800

i amy just want to send to one .
Posted
Comments
Herman<T>.Instance 13-Jun-14 2:06am    
first of all you select more columns then required? Second: use a CTE or a ROW_NUmber() function to tackle this problem
Hunain Hafeez 13-Jun-14 2:07am    
sir i don't know that how to use that and have tried a lot, if you could help me plz ?
Bernhard Hiller 13-Jun-14 2:54am    
And which one do you want to retrieve? Any criteria for selecting that one out of many possible values?
j snooze 13-Jun-14 17:00pm    
If you only want 1 record, you could just do "Select top 1 [ID],....."

1 solution

SELECT TOP 1 * FROM YOUR_STUFF ORDER BY NEWID()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900