gpt4 book ai didi

sql-server - 在姓氏搜索中添加撇号

转载 作者:行者123 更新时间:2023-12-04 00:20:39 24 4
gpt4 key购买 nike

我创建了一个过程,它将按姓氏返回申请人列表。我在搜索姓氏带有撇号的申请人时遇到问题(例如 O'Connor)。你能帮忙找到那些申请人吗:

下面是我的搜索代码:

if Rtrim(@FirstName) <> ''
begin
If(Len(@FirstName) < 30) and (CharIndex('%', @FirstName) = 0) and @FirstName != ''
Set @FirstName = char(39) + @FirstName + '%' + char(39)
end

if Rtrim(@LastName) <> ''
begin
If(Len(@LastName) < 60) and (CharIndex('%', @LastName) = 0) and @LastName != ''
Set @LastName = Char(39) + @LastName + '%' + char(39)
end

#At the end - --Now build dinamically the filter base on input parameters
if Rtrim(@FirstName) <> ''
select @Where = @Where + ' and a.FirstName like '+ Rtrim(@FirstName)

if Rtrim(@LastName) <> ''
select @Where = @Where + ' and a.LastName like '+ Rtrim(@LastName)

最佳答案

您的代码看起来像是在尝试构建动态 SQL WHERE 子句。把它停在那里然后扔掉,你的方法很危险而且容易出错。

您可能想按照以下方式做一些事情:

/* declare a few test variables */
DECLARE @FirstName varchar(30)
DECLARE @LastName varchar(60)
SET @FirstName = 'First''Name'
SET @LastName = 'Last''Name'

/* these variables are for dynamic SQL execution */
DECLARE @IntVariable int
DECLARE @SQLString nvarchar(500)
DECLARE @ParmDefinition nvarchar(500)

/* define a paramertized SQL query */
SET @SQLString =
N'SELECT
UserId
FROM
UserTable
WHERE
LastName LIKE ''%'' + @ln + ''%''
AND FirstName LIKE ''%'' + @fn + ''%''
'

/* define the used parameters and their types */
SET @ParmDefinition = N'@ln varchar(30), @fn varchar(60)'

/* execute dynamic SQL, syntax- and code-injection safely */
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@ln = @LastName, @fn = @FirstName

请务必阅读 MSDN on sp_executesql获取更多解释和示例。

关于sql-server - 在姓氏搜索中添加撇号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1681791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com