使用可以根据参数设置的变量的SELECT情况

时间:2015-05-05 14:07:57

标签: sql sql-server

我希望在使用来自另一个数据库的信息时从表中选择一个特定值,该数据库是根据当前数据库的值设置的。

所以选择一个案例来查找操作员代码并设置DB路径..然后使用相同的路径并整理结果。

DECLARE @DB varchar (1000)

CASE 
WHEN @Operator= 1 THEN SET @DB = '{SERVERNAME\ENTITY\DBNAME}'
WHEN @Operator= 2 THEN SET @DB = '{SERVERNAME2\ENTITY2\DBNAME2}'
WHEN @Operator= 3 THEN SET @DB = '{SERVERNAME3\ENTITY3\DBNAME3}'

Select transItem_item collate SQL_Latin1General_CI_AS
FROM Group_Transactions
INNER JOIN @DB.Table_Trans
ON (transItem.item_id collate SQL_Latin1General_CI-AS = Table_Trans.item_id)
Where ---Condition

3 个答案:

答案 0 :(得分:2)

如果这是TSQL(我猜测你的贪婪名称),那么你最好试用OPENQUERY来对另一个数据库服务器运行你的连接。如果您在同一服务器上查询数据库,则可以将查询构建为参数,然后使用EXEC运行它。

答案 1 :(得分:2)

控制流方法(可能是最有效的):

define node: {int id}
define edge: {node a , b ; int weight (default=1)}

define listNeighbours:
input: node n
output: list of neighbours

define dfs:
input: list nodes, list edges, node start, node end
output: list path

bool visited[length(nodes)]
fill(visited , false)

list stack
add(stack , start)
visited[start.id] = true

while ! isEmpty(stack)
     node c = first(stack)

     if c.id == end.id
          return stack

     list neighbours = listNeighbours(c)
     bool allVisited = true
     node next

     for node n in neighbours
          if visited[n.id]
                continue
          else
                allVisited = false
                next = n

      if allVisited
          pop(stack)
      else
          push(stack , next)

return null

单[条件]查询方法:

IF @Operator = 1
  BEGIN
    SELECT stuff
    FROM   Group_Transactions
     INNER
      JOIN "Server1\Instance1".Database1.Schema.Table_Trans
        ON Group_Transactions... = Table_Trans...
    WHERE  things...
    ;
  END
ELSE IF @Operator = 2
  BEGIN
    SELECT stuff
    FROM   Group_Transactions
     INNER
      JOIN "Server2\Instance2".Database2.Schema.Table_Trans
        ON Group_Transactions... = Table_Trans...
    WHERE  things...
    ;
  END
ELSE IF @Operator = 3
  BEGIN
    SELECT stuff
    FROM   Group_Transactions
     INNER
      JOIN "Server3\Instance3".Database3.Schema.Table_Trans
        ON Group_Transactions... = Table_Trans...
    WHERE  things...
    ;
  END
;

答案 2 :(得分:1)

Gvee的控制流方法可能很冗长,但它会起作用。如果你有一堆数据库,你可能想创建一个像@tbl_Databases这样的查找表。这是一个动态SQL解决方案:

DECLARE @Operator INT = 1,
        @DB VARCHAR(1000);

DECLARE @tbl_Databases TABLE (ID INT IDENTITY(1,1),DB VARCHAR(1000))
INSERT INTO @tbl_Databases(DB)
VALUES ('{SERVERNAME\ENTITY\DBNAME}'),('{SERVERNAME2\ENTITY2\DBNAME2}'),('{SERVERNAME3\ENTITY3\DBNAME3}');

SELECT @DB = DB
FROM @tbl_Databases
WHERE ID = @Operator

SELECT @DB

SELECT
(
'SELECT transItem_item COLLATE SQL_Latin1General_CI_AS
FROM Group_Transactions
INNER JOIN ' + @DB + '.dbo.Table_Trans
ON (transItem.item_id collate SQL_Latin1General_CI-AS = Table_Trans.item_id)
Where 1 = 1'
)