1

我认为这真的很简单,但我找不到可行的方法。

基本上我想通过输入的参数进行报告搜索,即 WHERE 子句中的 IE。

例如,下面的参数是@ColumnName 和@SearchTerm

SELECT
OITM.[ItemCode] AS [Item Code],
OITM.[ItemName] AS [Item Name],
OITM.[FrgnName] AS [Merchandise Type],
OITM.[OnHand] AS [In Stock],
OITM.[IsCommited] AS [Customer Reserved], 
OITM.[Onorder] AS [On Order],
OITW.[AvgPrice] AS [Cost]

FROM OITW
 INNER JOIN OITM ON OITM.[ItemCode] = OITW.[ItemCode]

WHERE
OITM.(@ColumnName) LIKE '%(@SearchTerm)%'

这一定有可能吗?非常感谢。

4

2 回答 2

2

我并不总是喜欢鼓励使用动态 SQL,但以下内容将完成您想要完成的工作。

DECLARE @ColumnName varchar(10) = 'ItemName', @SearchTerm varchar(5) = 'pat', @sql varchar(1000) = ''

SELECT @sql = 'SELECT
OITM.[ItemCode] AS [Item Code],
OITM.[ItemName] AS [Item Name],
OITM.[FrgnName] AS [Merchandise Type],
OITM.[OnHand] AS [In Stock],
OITM.[IsCommited] AS [Customer Reserved], 
OITM.[Onorder] AS [On Order],
OITW.[AvgPrice] AS [Cost]

FROM OITW
 INNER JOIN OITM ON OITM.[ItemCode] = OITW.[ItemCode]

WHERE OITM.' + @ColumnName + ' LIKE ''%' + @SearchTerm + '%'''

EXEC (@sql)

以下是我将如何真正做到这一点,但你可能有不想这样做的理由。由你决定。

SELECT
OITM.[ItemCode] AS [Item Code],
OITM.[ItemName] AS [Item Name],
OITM.[FrgnName] AS [Merchandise Type],
OITM.[OnHand] AS [In Stock],
OITM.[IsCommited] AS [Customer Reserved], 
OITM.[Onorder] AS [On Order],
OITW.[AvgPrice] AS [Cost]

FROM OITW
 INNER JOIN OITM ON OITM.[ItemCode] = OITW.[ItemCode]

WHERE (OITM.ItemName LIKE '%' + @SearchTerm + '%'
    OR OITM.FrgnName LIKE '%' + @SearchTerm + '%')...

祝你好运!

于 2016-07-07T17:09:00.310 回答
1

尝试这个:

SELECT
OITM.[ItemCode] AS [Item Code],
OITM.[ItemName] AS [Item Name],
OITM.[FrgnName] AS [Merchandise Type],
OITM.[OnHand] AS [In Stock],
OITM.[IsCommited] AS [Customer Reserved], 
OITM.[Onorder] AS [On Order],
OITW.[AvgPrice] AS [Cost]

FROM OITW
 INNER JOIN OITM ON OITM.[ItemCode] = OITW.[ItemCode]

WHERE
OITM.(@ColumnName) LIKE '%' + @SearchTerm + '%'

请注意,您的参数必须是文本类型。

让我知道这是否有帮助。

于 2016-07-07T14:52:10.077 回答