简体   繁体   中英

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

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 .

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()

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

Eg: instead of table name use: [table name]

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM