这是通用的proc你在做什么?
CREATE proc p_count
@table sysname, @columns nvarchar(max), @value nvarchar(max), @separator char(1) = ','
-- expected format of @columns is comma separated names
-- embedded commas supported by using a different @separator
as
declare @sql nvarchar(max)
set @sql =
'select *,
case when ' + replace(@columns, @separator, '=' + QuoteName(@value,'''') +
' then 1 else 0 end + case when ') + '=' + QuoteName(@value,'''') + ' then 1 else 0 end
from ' + quotename(@table)
--print @sql
exec (@sql)
GO
用法:
exec p_count 'have', 'col1|[col2]|col3', 1, '|'
exec p_count 'have', 'col1,col2,col3', 1
这种交替版本将一个可选参数,并更新与计数相同的表中的列。
CREATE proc p_count
@table sysname, @columns nvarchar(max), @value nvarchar(max), @separator char(1) = ',', @updateto sysname = null
-- expected format of @columns is comma separated names
-- embedded commas supported by using a different @separator
as
declare @sql nvarchar(max)
set @sql =
case when @updateto is null then 'select' else 'update x set ' + quotename(@updateto) + '=' end +
' case when ' + replace(@columns, @separator, '=' + QuoteName(@value,'''') +
' then 1 else 0 end + case when ') + '=' + QuoteName(@value,'''') + ' then 1 else 0 end
from ' + quotename(@table) + ' x'
print @sql
exec (@sql)
GO
用法(更新N_1):
exec p_count 'have', 'col1,col2,col3', 1, ',', 'N_1'
select * from have
它通常是一个迹象,表明你的数据模型是错的,如果你正在寻找在多个列中的数据相同的“种”。 – 2011-01-13 11:37:49