這是通用的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