我可以在使用SQL的Select Case / If语句中使用DDL命令吗?

时间:2016-01-27 21:59:13

标签: mysql sql sql-server

例如:

SELECT
  col A,
  col B,
  CASE
    WHEN col C = 't'
      THEN (DDL_STATEMENT_Here(Eg:ALTER))
      ELSE (DDL_statement_here(Eg:CREATE))
  END || col D || col E || col F ... etc 
FROM table;

1 个答案:

答案 0 :(得分:0)

您可能需要循环遍历表的行,并为每行执行DDL。可以像这样使用游标或表变量

DECLARE @dummy_table TABLE (
    col_c CHAR
    ,rnum INT
    )
DECLARE @rowcount INT = 1
DECLARE @col_c CHAR

INSERT INTO @dummy_table
SELECT [col C]
    ,ROW_NUMBER() OVER (
        ORDER BY [col C]
        ) rnum
FROM TABLE

WHILE (
        SELECT COUNT(1)
        FROM @dummy_table
        ) <> 0
BEGIN
    SELECT @col_c = [col C]
    FROM @dummy_table
    WHERE rnum = @rowcount

IF @col_c = 't'
BEGIN
    --ALTER STATEMENT
END
ELSE
BEGIN
    --CREATE STATEMENT
END

DELETE
FROM @dummy_table
WHERE rnum = @rowcount
SET @rowcount = @rowcount + 1
END