在存储过程中需要帮助以进行选择查询

时间:2012-10-25 12:14:02

标签: sql-server

我正在尝试根据名字和姓氏获取数据。除了一个DB中的少量额外数据外,我有两个DB副本。以下是相同的存储过程。问题是我想要获取数据的第一部分(即,如果我搜索ar它应该显示以ar开头的名称,而不是像Sharon那样在中间)。查询工作正常,只有一个db&而不是另一个。

   ALTER PROCEDURE [dbo].[SEARCH]
(
@firstName nvarchar(50),
@lastName nvarchar(50),
@state nvarchar(50),
@county nvarchar(50),
@searchspan nvarchar(5)
)
AS

BEGIN 
declare @queryString nvarchar(max)
declare @countyId nvarchar(50)
SET QUOTED_IDENTIFIER OFF 

Create table #temp1(
county nvarchar(50) NULL,
ID nvarchar(50) NULL,
name nvarchar(200) NULL,
state nvarchar(50) NULL,
FirstName nvarchar(50) NULL,
LastName nvarchar(50) NULL,
county nvarchar(50) NULL,
)
set @queryString = 'insert into #temp1 select  distinct a.Source as county, a.ID as ID, a.FirstName +'' ''+ a.LastName as name, ''' +
 @state +''' as state,a.FirstName,a.LastName,b.county, from Person a, CountySite b where 1=1 and a.Source=b.sourcecounty '

 if(@searchspan<>'')
 BEGIN
 set @queryString = @queryString  = 1'
 END
  EXECUTE  sp_executesql  @queryString
  set @queryString ='select county, ID, name, state,col_FirstName,col_LastName,col_county, from #temp1 where 1=1 '
 if(@firstName <> '')
BEGIN 
 set @queryString = @queryString+ ' and UPPER(col_FirstName) like ''' +@firstName +'%'''
END
if(@lastName <> '')
BEGIN 
 set @queryString = @queryString + ' and UPPER(col_LastName) like ''' +@lastName +'%'''
drop table #temp1
END

2 个答案:

答案 0 :(得分:0)

您是否有分析器,以便您可以看到正在第二个数据库上执行的查询?只是为了确保它是一样的。只是为了咧嘴笑,你可能想尝试在DB上删除并重新执行SP。

答案 1 :(得分:0)

TSQL不区分大小写,您不需要使用UPPER

同时将您的查询更改为

set @queryString = @queryString + ' and col_LastName like @lastName +'%'

试试这个

SET @queryString = @queryString + ' AND col_LastName  LIKE '''+@lastName +'%'''