vb.net 如何处理Sql server CREATE TABLE的数据库名称中的空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29076871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:53:06  来源:igfitidea点击:

How to handle spaces in database name for Sql server CREATE TABLE?

sql.netsql-serverdatabasevb.net

提问by User1162527

I have the following code and I use it in a vb.net project. this works well if there is no space in the database name. for example if the database name is "SampleCompany" it works fine but if the database name changes to "Sample Company" we recive an error in this section of sql command : "BEGIN CREATE TABLE " & cn.Database. We must be able to handle database names with/without spaces .

我有以下代码,并在 vb.net 项目中使用它。如果数据库名称中没有空格,这很有效。例如,如果数据库名称是“SampleCompany”,它工作正常,但如果数据库名称更改为“Sample Company”,我们会在 sql 命令的这一部分收到错误:“BEGIN CREATE TABLE”& cn.Database。我们必须能够处理带/不带空格的数据库名称。

any suggestion to solve this problem ? Thank you.

有什么建议可以解决这个问题吗?谢谢你。

cn.Database="Sample Company"

sqlCreate = "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE      TABLE_NAME = 'Cloud_UserSetting' AND TABLE_CATALOG ='" & cn.Database & "') " & _
            "BEGIN CREATE TABLE " & cn.Database & ".dbo.Cloud_UserSetting(CloudId int NOT NULL, Name varchar(100) NOT NULL," & _
            "Setting varchar(250) NULL " & _
            "CONSTRAINT PK_Cloud_UserSetting PRIMARY KEY CLUSTERED(CloudId,Name)) END"
command = New SqlCommand(sqlCreate, cn)
command.ExecuteNonQuery()

回答by Tharif

use square brackets to contain the column names and table names.

使用方括号包含列名和表名。

E.g.: instead of table nameuse: [table name]

例如:而不是table name使用:[table name]

回答by Md. Suman Kabir

You can simply use square brackets in your database name like below :

您可以简单地在数据库名称中使用方括号,如下所示:

cn.Database="[Sample Company]"

sqlCreate = "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE      TABLE_NAME = 'Cloud_UserSetting' AND TABLE_CATALOG ='" & cn.Database & "') " & _
            "BEGIN CREATE TABLE " & cn.Database & ".dbo.Cloud_UserSetting(CloudId int NOT NULL, Name varchar(100) NOT NULL," & _
            "Setting varchar(250) NULL " & _
            "CONSTRAINT PK_Cloud_UserSetting PRIMARY KEY CLUSTERED(CloudId,Name)) END"
command = New SqlCommand(sqlCreate, cn)
command.ExecuteNonQuery()