Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
n3tx
Starting Member
3 Posts |
Posted - 2009-11-09 : 21:13:30
|
| Hello, I am having some problems with a search query.The problem I am having is that I get duplicate values when I am joining two tables.Everything worked fine until I joined a second table (Addresses)Table Companies (ID (unique), CompanyName, Orgnumber ...)Table Addresses (Company_ID (not unique), Address .. )-- table can have more than one address with the same Company_IDHere is my sp:ALTER PROCEDURE [dbo].[sp_GetCompaniesByKeywords] @KeyWhat varchar(150) = NULL, -- what to search for@KeyWhere varchar(150) = NULL, -- where to search@PageSize int = NULL, -- page size@PageNumber int = NULL -- current page ASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.SET NOCOUNT ON;DECLARE @RowStart intDECLARE @RowEND intIF (@PageNumber > 0)BEGINIF (@PageNumber <=1)SET @RowEND = @RowStart + @PageSize +1SET @PageNumber = @PageNumber -1SET @RowStart = @PageSize * @PageNumber+1SET @RowEND = @RowStart + @PageSize - 1;DECLARE @sql nvarchar(4000)SELECT @sql = 'Select DISTINCT ROW_NUMBER() OVER (ORDER BY C.[Name]) AS RowNumber, COUNT(*) OVER() AS Count, c.ID, C.[Name] AS CompanyName, C.Orgnumber AS orgnr, cat.Name AS GenreFROM Companies as CJOIN Categories AS cat ON cat.ID = c.Genre_IDJOIN Addresses AS a ON a.CompanyID = C.ID WHERE 1=1'IF (@KeyWhat IS NOT NULL AND @KeyWhat <> '')SELECT @sql = @sql + ' AND C.[Name] LIKE ' + quotename('%' + @KeyWhat + '%', '''') +' OR cat.[Name] LIKE ' + quotename('%' + @KeyWhat + '%', '''') + ' OR C.Orgnumber LIKE ' + quotename(@KeyWhat + '%', '''')IF (@KeyWhere IS NOT NULL AND @KeyWhere <> '')SELECT @sql = @sql + ' AND a.address LIKE ' + quotename('%' + @KeyWhere + '%','''') +' OR a.zipcode LIKE ' + quotename('%' + @KeyWhere + '%','''') +' OR a.county LIKE ' + quotename('%' + @KeyWhere + '%','''') +' OR a.othertext LIKE ' + quotename('%' + @KeyWhere + '%','''')--PRINT @sqlCREATE TABLE #Result(RowNumber int,[Count] int,id int,companyName varchar(150),orgnumber varchar(20),kategori varchar(100))INSERT INTO #Result(rownumber, [count], id, companyname, orgnumber, kategori)EXEC sp_executeSQL @sqlSELECT * From #Result WHERE RowNumber Between @RowStart and @RowENDDROP Table #ResultENDEND// Daniel |
|
|
|
|
|
|
|