-1

I have two tables:

Table 1:

centers machines
------- --------
center1  machine1
center2  machine2
center2  machine3

Table 2:

operation center1 center2 center3 ...
--------- ------- ------- ------- ...
oper1     ok       ok
oper2     ok              ok
oper3     ok

Selecting a machine (via combobox) from first table, puts me in a center. The operations from Table 2 are specific to each center as shown. So after selecting the machine from table one, passing the center value to a variable like "center" (by Executescalar() method) I want to do:

SELECT operation from dbo.operations where "center" != null

this should return the only the operations from table 2 which are specific to "center". Does anyone know how this can be achieved?

4

2 回答 2

1

首先,在我真正回答你的问题之前,我会指出你真的真的真的需要研究normalization的概念,如果可能的话,修复你的表结构。您的操作表应该包含三列 - 操作、中心和状态 - 重复列如 Center1、Center2、Center3 ... 是糟糕设计的一个明显例子。除了更高效、更易于维护之外,规范化表还可以消除您需要更改查询中的列名的整个问题。

话说回来:

如果您正在使用一个SqlCommand对象来执行您的查询,并且您正在CommandText为该对象分配一个属性,那么您可以使命令文本成为您想要的任何内容。例如,您只需要使用String.Format插入正确的列名。您不能使用查询参数来更改列名,因此您只能动态生成 SQL 语句:

cmd.CommandText = string.Format("SELECT operation FROM dbo.Operations WHERE {0} IS NOT NULL", center);

请注意,什么都不会!= NULL:所有与NULLSQL 中的比较都返回 false(1 = NULL即为 false,1 != NULL也为 false)。您需要使用ISandIS NOT来比较NULL.

于 2012-09-11T14:34:21.697 回答
0

我不知道您使用的是哪种语言,但我想不出一种可以让您参数化列名的语言。

要执行您想要执行的操作,您必须使用动态 SQL,如果您不知道自己在做什么,这可能会非常危险,因此请自行承担风险。

于 2012-09-11T14:32:45.050 回答