如何根据输入参数动态添加一组列?

时间:2014-07-08 18:12:59

标签: sql vb.net

我需要根据variouse输入参数添加或删除大约20列。我知道我可以在CASE语句中包装每一行,但是当我需要为列集10添加10列时,这是一堆额外的代码。是一个动态SQL怪物的答案吗?

以下是我正在尝试做的一个示例 - 当最终用户需要列集1时返回5个特定列:

DECLARE @AddColumns AS NVARCHAR(20) = 'Column Set 1'

SELECT 
    col1
    , col2
    , CASE WHEN @AddColumns = 'Column Set 1' OR @AddColumns = 'Include All Columns'
        THEN col3, col4, col5, col6, col7
    END 
    , CASE WHEN @AddColumns = 'Column Set 2' OR @AddColumns = 'Include All Columns'
        THEN col8, col9, col10
    END
    , col11

FROM MyTable

2 个答案:

答案 0 :(得分:0)

试试这个动态SQL

DECLARE @AddColumns AS NVARCHAR(20) = 'Column Set 1'
DECLARE @SQL VARCHAR(5000)

SET @SQL = 'SELECT   col1, col2 '
IF @AddColumns = 'Column Set 1' OR @AddColumns = 'Include All Columns'
    SET @SQL = @SQL + ', col3, col4, col5, col6, col7 '
IF @AddColumns = 'Column Set 2' OR @AddColumns = 'Include All Columns'
    SET @SQL = @SQL + ', col8, col9, col10 '
SET @SQL = @SQL + ',col11 FROM MyTable'

EXEC (@SQL)

答案 1 :(得分:0)

在权衡动态SQL,ExecuteSql,在VB中构建SQL字符串或编辑生成的VB数据集的选项后,我在VB中动态构建SQL字符串。我正在寻找一种在SQL中执行此操作的“简单”方法。尽管可以在SQL中完成,但在VB中使用它是“更清洁”的。 (对不起,我应该提到VB在原始问题中使用的查询。)想象一下,每个集合中添加大约5-10列,多个连接,参数化过滤器等许多列集。如果构建各种SQL查询,我在这里做什么零件和它们根据输入参数将它们附加在一起。

' Build the various chunks of SQL as CDATA strings
Dim selectPrimaryColumns As String =
<![CDATA[
    /*
        My Report
    */
    USE DatabaseName

    SELECT col1
        , col2
]]>.Value

selectColumnSetA
<![CDATA[
        -- Column Set A
        , col3
        , col4
]]>.Value

selectColumnSetB
<![CDATA[
        -- Column Set B
        , col5
        , col6
]]>.Value

Dim selectFilters As String =
<![CDATA[
    FROM MyTable t
      -- with many joins

    WHERE t.Date BETWEEN @StartDate AND DATEADD(DAY, 1, @EndDAte)
      -- and many more parameterized filters.

]]>.Value

' Set the first part of the query
Dim fullQuery As String = selectPrimaryColumns

' Conditionally add the various column sets
SELECT CASE myParameter
 CASE "ColumnSetA"
    fullQuery = fullQuery & selectColumnSetA
 CASE "ColumnSetB"
    fullQuery = fullQuery & selectColumnSetB

' Add the last part of the query
fullQuery = fullQuery & selectFilters

我现在有一个SQL查询字符串,可以传递给SQL Command对象。