我想编写一个过程,如果该列不存在,则将新列添加到表中。我最初是为MySQL编写的,并且可以成功运行,但是当我尝试为SQL SERVER编写相同的过程时,出现了一些语法错误,而且我不确定SQL SERVER过程是否正确,是否会执行相同的工作MySQL的一个。
MySQL过程:
SET @dbname = DATABASE();
SET @tablename = "my_table";
SET @columnname = "my_field";
SET @preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = @tablename)
AND (table_schema = @dbname)
AND (column_name = @columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT UNSIGNED NOT NULL;")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
SQL SERVER过程:
DECLARE @dbname varchar(128), @tablename varchar(11), @columnname varchar(11), @preparedStatement varchar(max);
SET @dbname = DB_NAME();
SET @tablename = "my_table";
SET @columnname = "my_field";
SET @preparedStatement = (SELECT CASE(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = @tablename)
AND (table_schema = @dbname)
AND (column_name = @columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT UNSIGNED NOT NULL;")
));
EXEC sp_prepare @preparedStatement;
第12行的GREATER THAN运算符出现语法错误:
信息102,级别15,状态1,第12行在“>”附近的语法不正确。
答案 0 :(得分:3)
您的SQL有很多错误:
首先,SQL Server对文字字符串使用单引号('
)。
CASE
表达式使用格式CASE WHEN {expr} THEN {expr} ELSE [WHEN {expr} THEN {expr}] [THEN {expr}] END
或CASE {expr} WHEN ...
;您的版本格式非常错误。
UNSIGNED
数据类型在SQL Server中不存在。您只需签名(tinyint
除外,它是0-255)。
此外,sp_prepare
不是正确的函数,您想要sp_executesql
。
最后,为了避免注入,我用QUOTENAME
包裹了对象名称,并将数据类型更改为sysname
(又名nvarchar(128)
),并将文字字符串设置为{{1} }(nvarchar
,而不是N''
)。这会让您:
''
答案 1 :(得分:2)
查看SQL并在IMO中使其更易于阅读的另一种方法是将CASE语句转换为存在检查
DECLARE @dbname varchar(128), @SchemaName varchar(30), @tablename varchar(30), @columnname varchar(30), @preparedStatement nvarchar(max);
SET @dbname = DB_NAME();
SET @SchemaName = 'dbo';
SET @tablename = 'myTable';
SET @columnname = 'myColumn';
IF NOT EXISTS(
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA LIKE @SchemaName
AND TABLE_NAME LIKE @tablename
AND COLUMN_NAME LIKE @columnname
)
BEGIN
SET @preparedStatement = CONCAT('ALTER TABLE ', @tablename, ' ADD ', @columnname, ' INT UNSIGNED NOT NULL;')
EXEC sp_executesql @preparedStatement;
END