【问题标题】:Inserting data into a SQL Server table将数据插入 SQL Server 表
【发布时间】:2014-11-29 17:08:57
【问题描述】:

尝试向表中插入数据时出现错误,因为我不知道如何插入主键。我得到的错误是:

操作数类型冲突:int 与 uniqueidentifier 不兼容

我的代码:

USE BeachTennis7

INSERT INTO dbo.player (playerfname, playerlname, gender, age, [prior rank], player_id)
VALUES ('Dan', 'McClure', 'M', 21, 1, 0);

我了解int 值不能转换为键,我只是不知道如何声明主键。谢谢!

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    您需要将变量声明为唯一标识符,然后将其添加到插入语句中。

    DECLARE @playerId uniqueidentifier
    SET @playerId = NEWID()
    
    INSERT INTO dbo.player (playerfname,playerlname,gender,age,[prior rank],player_id)
    VALUES ('Dan','McClure','M',21,1, @playerId);
    

    【讨论】:

    • 非常感谢,很有道理。
    • @user3325875,考虑在 player_id 列上添加一个值为 NEWSEQUENTIALID() 的默认约束。这将避免在插入语句中指定列和值的需要,并且比随机 GUID 值执行得更好。
    • @user3325875:如果这个答案帮助你解决了你的问题,那么请accept this answer。这将表达您对花费自己的时间帮助您的人们的感激之情。
    【解决方案2】:

    使用这个

    INSERT INTO dbo.player (playerfname, playerlname, gender, age, [prior rank], player_id) 值 ('Dan', 'McClure', 'M', 21, 1, NEWID());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-19
      • 2016-09-15
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多