【发布时间】:2015-01-08 20:56:48
【问题描述】:
我写了一个存储过程,得到:
- "SearchKeys" - 用 ',' "key1,key2" 分隔的搜索键
- "ToSearch" - 要搜索的表用 ',' 分隔,':' 后面的列用 '.' 分隔"table1:column1.column2,table2:column1.column2"
最后,如果找到了键,过程会返回带有表名和行 ID 的表。
代码如下:
--Search keys in tables
CREATE PROCEDURE [dbo].[Search_All]
(
@SearchKeys nvarchar(50), --Keys to search separated by ','
@ToSearch varchar(200) --Tables to search in separated by ',' with colums after ':' separated by '.'
)
AS
BEGIN
--create table with found values
CREATE TABLE #Results (TargetId int, DBName varchar(20))
--Split SearchKeys to Keys
WHILE LEN(@SearchKeys) > 0
BEGIN
DECLARE @Key NVARCHAR(25)
IF CHARINDEX(',',@SearchKeys) > 0
SET @Key = SUBSTRING(@SearchKeys,0,CHARINDEX(',',@SearchKeys))
ELSE
BEGIN
SET @Key = @SearchKeys
SET @SearchKeys = ''
END
--Split ToSearch to Tables
WHILE LEN(@ToSearch) > 0
BEGIN
DECLARE @TableAndColums VARCHAR(200)
IF CHARINDEX(',',@ToSearch) > 0
SET @TableAndColums = SUBSTRING(@ToSearch,0,CHARINDEX(',',@ToSearch))
ELSE
BEGIN
SET @TableAndColums = @ToSearch
SET @ToSearch = ''
END
SET @ToSearch = REPLACE(@ToSearch,@TableAndColums + ',' , '')
--Split @TableAndColums to Table and Colums
--Select Table
DECLARE @Table VARCHAR(25)
SET @Table = SUBSTRING(@TableAndColums,0,CHARINDEX(':',@TableAndColums))
SET @TableAndColums = REPLACE(@TableAndColums,@Table + ':' , '')
--Split to Colums
WHILE LEN(@TableAndColums) > 0
BEGIN
DECLARE @Column VARCHAR(25)
IF CHARINDEX('.',@TableAndColums) > 0
SET @Column = SUBSTRING(@TableAndColums,0,CHARINDEX('.',@TableAndColums))
ELSE
BEGIN
SET @Column = @TableAndColums
SET @TableAndColums = ''
END
BEGIN
--insert result in to #Results table
INSERT INTO #Results
EXEC
(
'SELECT ' + @Table + '.Id AS ''TargetId'', '''+@Table+''' AS ''DBName''
FROM ' + @Table +
' WHERE ' + @Column + ' LIKE N''%' + @Key + '%'''
)
END
SET @TableAndColums = REPLACE(@TableAndColums,@Column + '.' , '')
END
END
SET @SearchKeys = REPLACE(@SearchKeys,@Key + ',' , '')
END
--return found values
SELECT DISTINCT TargetId , DBname FROM #Results
END
由于某种原因,它只搜索第一个键而忽略所有其余键。我不知道为什么会这样。请帮忙!
【问题讨论】:
标签: sql sql-server search stored-procedures search-engine