你能给我一些指示(或指向谷歌搜索条件的正确方向)?在存储过程中,我有一个参数@TAG
(字符串)。我收到了(#14038314,14040071)' (例如)来自另一个无法更改的应用程序。在存储过程中,我需要分开'(14038314,14040071)'在每个字符串值周围加上引号,重建它,去掉外部引号,去掉parens并将它传递给下面查询中的@TAG,以便它看起来像下面注释掉的那一行?
SELECT
V.NAME AS VARIETY, TAGID
FROM
mfinv.dbo.onhand h
INNER JOIN
mfinv.dbo.onhand_tags t on h.onhand_id = t.onhand_id
INNER JOIN
mfinv.dbo.onhand_tag_details d on t.onhand_tag_id = d.onhand_tag_id
INNER JOIN
mfinv.dbo.FM_IC_PS_VARIETY V ON V.VARIETYIDX = d.VARIETYIDX
LEFT JOIN
mfinv.dbo.FM_IC_TAG TG ON TG.TAGIDX = t.TAGIDX
WHERE
h.onhand_id = (SELECT onhand_id FROM mfinv.dbo.onhand
WHERE onhand_id = IDENT_CURRENT('mfinv.dbo.onhand'))
AND TG.ID IN (@TAG)
--AND TG.ID IN ('14038314','14040071')
答案 0 :(得分:0)
您可以像这样使用动态SQL
DECLARE @TAG Nvarchar(MAX)='14038314,14040071'
set @TAG=''''+REPLACE(@TAG,',',''',''')+''''
--select @TAG
DECLARE @SQL NVARCHAR(MAX)=N'
Select V.NAME AS VARIETY, TAGID
FROM mfinv.dbo.onhand h
INNER JOIN mfinv.dbo.onhand_tags t on h.onhand_id = t.onhand_id
INNER JOIN mfinv.dbo.onhand_tag_details d on t.onhand_tag_id = d.onhand_tag_id
INNER JOIN mfinv.dbo.FM_IC_PS_VARIETY V ON V.VARIETYIDX = d.VARIETYIDX
LEFT JOIN mfinv.dbo.FM_IC_TAG TG ON TG.TAGIDX = t.TAGIDX
WHERE h.onhand_id = (SELECT onhand_id FROM mfinv.dbo.onhand
WHERE onhand_id = IDENT_CURRENT (''mfinv.dbo.onhand''))
AND TG.ID IN ('+@TAG+')'
PRINT @SQL
EXEC (@SQL)
答案 1 :(得分:0)
这就是我的所作所为。谢谢大家的回复。感谢dasblinkenlight回答“如何替换sql server中列的第一个和最后一个字符?”。感谢SQLMenace回答“如何在不创建函数的情况下在SQL Server中拆分分隔字符串?”。
以下是删除括号的方法:
@Tag nvarchar(256)
SET @Tag = SUBSTRING(@Tag, 2, LEN(@Tag)-2)
以下是我分割和重建@Tag的方法:
AND TG.ID in
(
SELECT SUBSTRING(',' + @Tag + ',', Number + 1,
CHARINDEX(',', ',' + @Tag + ',', Number + 1) - Number -1)AS VALUE
FROM master..spt_values
WHERE Type = 'P'
AND Number <= LEN(',' + @Tag + ',') - 1
AND SUBSTRING(',' + @Tag + ',', Number, 1) = ','
)