我有以下字符串转换为where
子句。
给定字符串:
DECLARE @String VARCHAR(MAX) = 'Dateofjoining = '2015-01-01' AND Firstname = ''Sam'' AND Lastname = ''Mak'' AND PhoneNumber = 123'
注意:用于员工表的条件检查的给定字符串,我只是获取员工的特定firstName
和LastName
的记录。现在我想将SOUNDEX()
函数添加到字符串中给定值的两端。所以预期的WHERE
子句应该如下所示。
预期结果:
SELECT *
FROM dbo.Employee2
WHERE Dateofjoining = '2015-01-01'
AND SOUNDEX(Firstname) = SOUNDEX('Sam')
AND SOUNDEX(LastName) = SOUNDEX('Mak')
AND PhoneNumber = 123;
答案 0 :(得分:1)
以下查询可以完成您的工作 -
DECLARE @String VARCHAR(MAX) = 'Dateofjoining = ''2015-01-01'' AND Firstname = ''Sam'' AND Lastname = ''Mak'' AND PhoneNumber = 123'
DECLARE @Sql VARCHAR(MAX) = 'SELECT *
FROM dbo.Employee2
WHERE '
SET @String = SUBSTRING(@String,1,PATINDEX('%AND%',@String)-1)+' AND '+
'SOUNDEX('+REPLACE(SUBSTRING(@String,PATINDEX('%AND%',@String)+3,dbo.Pos(@string,'''',1)+1),' = ',')= SOUNDEX(')+')'+' AND '+
'SOUNDEX('+REPLACE(SUBSTRING(@String,dbo.Pos(@string,'AND',2)+4,dbo.Pos(@String,'AND',3)-dbo.Pos(@String,'AND',2)-4),' = ',') = SOUNDEX(')+')'+' AND '+
SUBSTRING(@string,dbo.Pos(@String,'AND',3)+4,LEN(@String))
SELECT @Sql + @string
查找'
-
CREATE FUNCTION dbo.Pos(@string VARCHAR(MAX),@delim VARCHAR(10),@occur INT)
RETURNS INT
AS
BEGIN
DECLARE @pos int, @counter int, @ret int
SET @pos = CHARINDEX(@delim, @string)
set @counter = 1
if @occur = 1 set @ret = @pos
else
begin
while (@counter < @occur)
begin
select @ret = CHARINDEX(@delim, @string, @pos + 1)
set @counter = @counter + 1
set @pos = @ret
end
end
RETURN @ret
END
修改:根据要求进行更改。
答案 1 :(得分:0)
尝试这样的事情
create table #temp(Num int,FName Varchar(50),SName varchar(50))
insert into #temp values(1,'Sam','Mark')
insert into #temp values(1,'Jan','Feb')
DECLARE @Con1 VARCHAR(MAX)
DECLARE @Val1 VARCHAR(MAX)
DECLARE @Con2 VARCHAR(MAX)
DECLARE @Val2 VARCHAR(MAX)
set @Con1 = 'FName'
set @Val1 = 'Sam'
set @Con2 = 'SName'
set @Val2 = 'Mark'
DECLARE @str VARCHAR(MAX)
SET @str='SELECT * FROM #temp
WHERE SOUNDEX('+@Con1+') = SOUNDEX('''+@Val1+''')
AND SOUNDEX('+@Con2+') = SOUNDEX('''+@Val2+''')'
Execute(@str)
drop table #temp