これは一般的なものですか?
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
それは通常、あなたが複数の列のデータの同じ「種類」を探しているなら、あなたのデータモデルが間違っている兆候です。 –