我正在使用sql server 2012,我有一个这样的表:
FieldName FieldValue
DivisionId 1
DivisionId 2
DivisionId 3
CompanyId 2
CompanyId 3
LocationId 1
我想要的是连接列并形成像这样的
的where子句查询(DivisionId=1 OR DivisionId=2 OR DivisionId=3) AND
(CompanyId=2 OR CompanyId=3) AND
(LocationId = 1)
我能弄清楚的是,我需要连接像这样的列值
DECLARE @Query VARCHAR(MAX)
SELECT @Query =
ISNULL(@Query,'') + IIF(@Query IS NOT NULL, ' AND ', '') + CONCAT(DF.FieldName,'=',DA.FieldValue)
FROM TABLE
SELECT @Query;
但是这段代码不会处理OR条件。
答案 0 :(得分:1)
尝试以下解决方案:
DECLARE @eav TABLE (
FieldName NVARCHAR(128) NOT NULL,
FieldValue VARCHAR(50) NOT NULL
)
INSERT @eav (FieldName, FieldValue)
SELECT 'DivisionId', 1 UNION ALL
SELECT 'DivisionId', 2 UNION ALL
SELECT 'DivisionId', 3 UNION ALL
SELECT 'CompanyId ', 2 UNION ALL
SELECT 'CompanyId ', 3 UNION ALL
SELECT 'LocationId', 1
DECLARE @Predicate NVARCHAR(MAX) = N''
SELECT @Predicate = @Predicate
+ CASE WHEN rn_asc = 1 THEN ' AND ' + FieldName + ' IN (' + LTRIM(FieldValue) ELSE '' END
+ CASE WHEN rn_asc > 1 THEN ', ' + LTRIM(FieldValue) ELSE '' END
+ CASE WHEN rn_desc = 1 THEN ') ' ELSE '' END
FROM (
SELECT *,
rn_asc = ROW_NUMBER() OVER(PARTITION BY x.FieldName ORDER BY x.FieldValue),
rn_desc= ROW_NUMBER() OVER(PARTITION BY x.FieldName ORDER BY x.FieldValue DESC)
FROM @eav x
) y
ORDER BY FieldName, FieldValue
SELECT @Predicate = STUFF(@Predicate, 1, 5, '')
SELECT @Predicate
-- Results: CompanyId IN (2, 3) AND DivisionId IN (1, 2, 3) AND LocationId IN (1)
然后您可以使用@Predicate
创建动态SQL SELECT
语句(例如)
DECLARE @SqlStatement NVARCHAR(MAX)
SET @SqlStatement = 'SELECT ... FROM dbo.Table1 WHERE ' + @Predicate
EXEC sp_executesql @SqlStatement