返回另一列是否为空的计算位列

发布于 2024-08-13 13:58:03 字数 315 浏览 4 评论 0原文

我尝试使用这个计算列:

CREATE TABLE dbo.Item
(
    ItemId int NOT NULL IDENTITY (1, 1),
    SpecialItemId int NULL,
    --I tried this
    IsSpecialItem AS ISNULL(SpecialItemId, 0) > 0, 
    --I tried this
    IsSpecialItem AS SpecialItemId IS NOT NULL
    --Both don't work
)  ON [PRIMARY]

I try to have this computed column:

CREATE TABLE dbo.Item
(
    ItemId int NOT NULL IDENTITY (1, 1),
    SpecialItemId int NULL,
    --I tried this
    IsSpecialItem AS ISNULL(SpecialItemId, 0) > 0, 
    --I tried this
    IsSpecialItem AS SpecialItemId IS NOT NULL
    --Both don't work
)  ON [PRIMARY]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮光之海 2024-08-20 13:58:03

这有效:

CREATE TABLE dbo.Item
(
    ItemId int NOT NULL IDENTITY (1, 1),
    SpecialItemId int NULL,
    IsSpecialItem AS
        CAST(CASE ISNULL(SpecialItemId, 0) WHEN 0 THEN 0 ELSE 1 END AS bit)
)

This works:

CREATE TABLE dbo.Item
(
    ItemId int NOT NULL IDENTITY (1, 1),
    SpecialItemId int NULL,
    IsSpecialItem AS
        CAST(CASE ISNULL(SpecialItemId, 0) WHEN 0 THEN 0 ELSE 1 END AS bit)
)
迷乱花海 2024-08-20 13:58:03

Mark Byer 的回答 导致 nvarchar 列出现错误,无论列是否为 <代码>int或nvarchar

CREATE TABLE dbo.Item
(
    ItemId int NOT NULL IDENTITY (1, 1),
    SpecialItemId [nvarchar](50) NULL,
    CAST(CASE WHEN SpecialItemId Is NULL THEN 0 ELSE 1 END AS bit)
      AS IsSpecialItem 
)

Mark Byer's answer causes an error with nvarchar columns, the following works regardless of whether column is int or nvarchar:

CREATE TABLE dbo.Item
(
    ItemId int NOT NULL IDENTITY (1, 1),
    SpecialItemId [nvarchar](50) NULL,
    CAST(CASE WHEN SpecialItemId Is NULL THEN 0 ELSE 1 END AS bit)
      AS IsSpecialItem 
)
水水月牙 2024-08-20 13:58:03

SQL Server 没有任何本机 true 布尔数据类型(从某种意义上说,您可以使用变量代替布尔表达式,例如 select * from Item where IsSpecialItem)。表示它的唯一方法是像 Mark 建议的那样,使用保留值(在这种情况下,您的查询将是 select * from Item where IsSpecialItem = 1)。

SQL Server doesn't have any native true boolean data type (in the sense that you could use a variable in place of a boolean expression, like select * from Item where IsSpecialItem). The only way you can represent it is with something like Mark suggests, using reserved values (in this case, your query would be select * from Item where IsSpecialItem = 1).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文