在 where 子句中使用位列

Using a bit column in a where clause

我正在编写一个非常简单的查询,我需要根据具有两个值的列检索记录:0 和 1。我没有意识到此列有位类型,因此当我编写查询时SQL 服务器给我消息

"Incorrect syntax near the keyword 'Primary'."

我的查询很简单:

select * from [table name]
where Primary = '1'

我已经尝试搜索该网站,但找不到合适的答案。顺便说一句,我只能从 table 检索数据。我不能声明变量或创建存储过程或任何类似的东西。当然,这不会那么复杂。请协助!

PRIMARY是保留字,需要加引号:

select * from [table name] where [Primary] = 1;

那是因为 primarya reserved word in SQL Server。你需要引用它:

select * from [table name] where [Primary] = 1

我强烈建议更改列名,以免与语言关键字冲突。 SQL服务器保留作品不足200个,余地很大

所以:

sp_rename '[table name].[primary]', 'prim', 'COLUMN';

问题与数据类型 bit 无关,错误实际上是 确切地 告诉您问题是什么:

Incorrect syntax near the keyword 'Primary'.

添加了重点。

PRIMARY 是一个 reserved keyword。理想情况下不要对对象名称使用关键字,但如果您“必须”,那么您 必须 分隔标识对象。事实上,你真的应该避免任何需要定界标识的对象名称:

SELECT {Your Columns} --Define the columns, don't use *
FROM dbo.[Table Name] --I hope you don't have white space in your object names too
WHERE [Primary] = 1; --Don't wrap bit/numerical values in quotes.