日期:2014-05-17 浏览次数:20470 次
ALTER PROCEDURE USP_GetResultByLike
@TableName nvarchar(20),--表名.
@FieldName nvarchar(20),--字段名.
@FieldVal nvarchar(50) --字段值.
AS
SET NOCOUNT ON
declare @sql nvarchar(max)
set @sql = 'select [FId] as [编号],[FBlotterDate] as [流水日期],[FWorkpadCateName] as [记事类],
[FModified] as [修改说明],[FContent] as [内容] from '+@TableName+ ' where '+@FieldName+' like %'''+@FieldVal+''' order by [FId]'
exec(@sql)
set @sql = 'select [FId] as [编号],[FBlotterDate] as [流水日期],[FWorkpadCateName] as [记事类],
[FModified] as [修改说明],[FContent] as [内容] from '+''''+@TableName+''''+ ' where '+''''+@FieldName+''''+' like '+''''+'%'+@FieldVal+''''+' order by [FId]'
exec(@sql)
--先看一下正常的语句
SELECT * FROM tablename WHERE fieldname LIKE '%test' ORDER BY FId
--如果想把上面的语句放到字符串中再用exec执行,步骤如下
--#1.把SQL中的'全部替换成''
SELECT * FROM tablename WHERE fieldname LIKE ''%test'' ORDER BY FId
--#2.放到变量中
DECLARE @sql NVARCHAR(max)
SET @sql = 'SELECT * FROM tablename WHERE fieldname LIKE ''%test'' ORDER BY FId'
--#3.替换参数(注意替换的参数必须都是字符类型),替换时直接: '+ @变量名 +'
DECLARE @变量名 NVARCHAR(10)
SET @变量名 = 'test'
SET @sql = 'SELECT * FROM tablename WHERE fieldname LIKE ''%'+ @变量名 +''' ORDER BY FId'
PRINT @sql
--所以你那个应该是
set @sql = 'select [FId] as [编号],[FBlotterDate] as [流水日期],[FWorkpadCateName] as [记事类],
[FModified] as [修改说明],[FContent] as [内容] from '+@TableName+ ' where '+@FieldName+' like ''%'+@FieldVal+''' order by [FId]'