英文:
What is the correct code to make the user put the column names inside the table in Databases via SQL?
问题
我使用这段代码让用户在数据库中输入列名 / 文本 =
"create table oop('"+id+"' varchar(30) not null,'"+name+"' varchar(20) not null,'"+lastname+"' varchar(20) notnull,'"+salary+"' varchar(30) not null) " ;
出现错误
正确的代码是什么,以便用户通过SQL在数据库中放置列名到表中?
英文:
I used this code to have the user put the column name in the database / text =
"create table oop('"+id+"' varchar(30) not null,'"+name+"' varchar(20) not null,'"+lastname+"' varchar(20) notnull,'"+salary+"' varchar(30) not null) " ;
is error
What is the correct code to make the user put the column names inside the table in Databases via SQL?
答案1
得分: 1
只需移除列名周围的单引号:它们代表字面字符串,而不是标识符:
"create table oop(" + id + " varchar(30) not null," + name + " varchar(20) not null," + lastname + " varchar(20) notnull, " + salary + " varchar(30) not null)";
另一方面,如果您的标识符包含特殊字符,那么您需要对它们进行引用:为此,请使用与您的数据库相关的引用字符:MySQL 需要反引号,SQL Server 使用方括号([]
),Postgres 和 Oracle 使用双引号""
。
英文:
Just remove the single quotes around the column name: they stand for literal strings, not for identifiers:
"create table oop(" + id + " varchar(30) not null," + name + " varchar(20) not null," + lastname + " varchar(20) notnull, " + salary + " varchar(30) not null)" ;
On the other hand, if your identifiers contain special characters, then you need to quote them: for this, use the relevant quoting character for your database: MySQL wants backticks, SQL Server has square brackets, ([]
), Postgres and Oracle use the double quote ""
.
答案2
得分: 0
创建一个类似以下的存储过程:
CREATE PROCEDURE sproc_BuildTable
@TableName NVARCHAR(128)
,@Column1Name NVARCHAR(32)
,@Column1DataType NVARCHAR(32)
,@Column1Nullable NVARCHAR(32)
AS
DECLARE @SQLString NVARCHAR(MAX)
SET @SQLString = 'CREATE TABLE ' + @TableName + ' ( ' + @Column1Name + ' ' + @Column1DataType + ' ' + @Column1Nullable + ') ON PRIMARY '
EXEC (@SQLString)
GO
可以像这样执行这个存储过程:
sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'
英文:
Make a PROCEDURE like:
CREATE PROCEDURE sproc_BuildTable
@TableName NVARCHAR(128)
,@Column1Name NVARCHAR(32)
,@Column1DataType NVARCHAR(32)
,@Column1Nullable NVARCHAR(32)
AS
DECLARE @SQLString NVARCHAR(MAX)
SET @SQString = 'CREATE TABLE '+@TableName + '( '+@Column1Name+' '+@Column1DataType +' '+@Column1Nullable +') ON PRIMARY '
EXEC (@SQLString)
GO
This stored procedure can be executed like this:
sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论