有没有更好的方法在动态查询中找到特定值?

时间:2017-09-20 09:23:42

标签: sql sql-server tsql dynamic

我正在尝试找出动态查询中是否存在值,目前我正在使用此解决方案:

DECLARE 
  @SQL NVARCHAR(MAX)
, @ISLN NUMERIC(9,0) = '967272'
SET @SQL = 
'SELECT * 
FROM ITEM 
LEFT OUTER JOIN SHIPMENT_DETAIL 
ON ITEM.ITEM = SHIPMENT_DETAIL.ITEM 
AND (SHIPMENT_DETAIL.COMPANY = ITEM.COMPANY OR ITEM.COMPANY IS NULL)  
WHERE (SHIPMENT_DETAIL.warehouse = N''SH'' ) 
ORDER BY ITEM.ITEM  ASC'
SELECT @SQL = STUFF (
    @SQL
    , 8
    , 1
    , 'INTERNAL_SHIPMENT_LINE_NUM'
)
DECLARE @TEMP TABLE (ISLN NUMERIC(9,0))
INSERT INTO @TEMP (ISLN)
EXEC SP_SQLEXEC @SQL
IF EXISTS (SELECT 1 FROM @TEMP WHERE ISLN = @ISLN)
SELECT 1
ELSE 
SELECT 0

动态SQL由其他软件生成,因此我无法更改输入数据。

有没有更好的方法在动态查询的特定列中查找特定值?

1 个答案:

答案 0 :(得分:0)

试试这个,希望它会对你有所帮助:

DECLARE 
  @SQL NVARCHAR(MAX)
, @ISLN NUMERIC(9,0) = '967272'
SET @SQL = 
'SELECT * 
FROM ITEM 
LEFT OUTER JOIN SHIPMENT_DETAIL 
ON ITEM.ITEM = SHIPMENT_DETAIL.ITEM 
AND (SHIPMENT_DETAIL.COMPANY = ITEM.COMPANY OR ITEM.COMPANY IS NULL)  
WHERE (SHIPMENT_DETAIL.warehouse = N''SH'' ) 
ORDER BY ITEM.ITEM  ASC'

SELECT @SQL = 'if exists (' + STUFF (
    @SQL
    , charindex('where', @sql) + 6
    , 0
    , 'INTERNAL_SHIPMENT_LINE_NUM = ' + cast(@isln as varchar(20)) + ' and '
) + ') select 1 else select 0;';
EXEC SP_SQLEXEC @SQL;