如何在单个SQL查询中选择foreach

时间:2015-09-21 14:45:40

标签: sql sql-server

我有一个问题,我尝试做一个foreach来选择多行并在每个行中做一个选择。

这是我的表:

| TRANSLATION_ID    | TABLE_NAME                | COLUMN_NAME   | ID_COLUMN     | CODELANGUE_COLUMN     |
|----------------   |-------------------------  |-------------  |-----------    |-------------------    |
| 1                 | CHAMPS_LANGUE             | VALUE1        | ZZZ           | CODELANGUE            |
| 2                 | DELAIS_LIBELLES           | VALUE2        | YYY           | CODELANGUE            |
| 3                 | MODELES_ENQUETES_LIGNES   | VALUE3        | XXX           | CODELANGUE            |
| ...               | ...                       | ...           | ...           |                       |

我想在SELECT之类的每个TABLE上执行多次CHAMPS_LANGUE , DELAIS_LIBELLES

FOREACH TABLE_NAME
 SELECT COLUM_NAME, ID_COLUM FROM TABLE_NAME WHERE CODELANGUE = 1

如果不是非常明确,请告诉我。 :)

1 个答案:

答案 0 :(得分:1)

修改@legendofawesomeness找到here的答案,使其与您的情况更相关

--Cursor for iterating
DECLARE @tableCursor       CURSOR
DECLARE @TABLE_NAME        NVARCHAR(255)
DECLARE @COLUM_NAME        NVARCHAR(255)
DECLARE @ID_COLUM          NVARCHAR(255)
DECLARE @CODELANGUE_COLUMN  NVARCHAR(255)

SET @tableCursor = CURSOR FOR SELECT TABLE_NAME, COLUM_NAME, ID_COLUMN, CODELANGUE_COLUMN FROM [tableData] -- Substitute with the name of your table as given in your question (which you didn't specify)

OPEN @tableCursor
FETCH NEXT FROM @tableCursor INTO @TABLE_NAME, @COLUM_NAME, @ID_COLUMN, @CODELANGUE_COLUMN
WHILE (@@fetch_status = 0)
BEGIN
   --dynamic sql
   DECLARE @sql NVARCHAR(max)

   --Your logic here...
   SET @sql = 'SELECT ' + @COLUM_NAME + ', ' + @ID_COLUM + ' FROM ' + @TABLE_NAME + ' WHERE ' + @CODELANGUE_COLUMN + ' = 1'
   EXEC dbo.sp_executesql @sql

FETCH NEXT FROM @tableCursor INTO @TABLE_NAME, @COLUM_NAME, @ID_COLUMN, @CODELANGUE_COLUMN
END

CLOSE @tableCursor
DEALLOCATE @tableCursor