字符串(varchar)如何传递到SQL存储过程?

Geo*_*rge 1 sql t-sql sql-server stored-procedures

我试图将字符串传递给存储过程.我的代码是:

CREATE PROCEDURE AddCondition
    @CondName varchar(50),
    @CondDesc varchar(50)
AS
    DECLARE @CondID int

    --This code gets the next ID for the table
    SET @CondID = (SELECT MAX([Condition ID]) FROM [dbo].[Tube Conditions]) + 1
    SET @CondID = ISNULL(@CondID,1)

    --This code adds records to the table
    INSERT INTO [dbo].[Tube Conditions] ([Condition ID],[Condition Name],[Description])
    VALUES (@CondID, @CondName, @CondDesc)
GO
Run Code Online (Sandbox Code Playgroud)

我尝试执行:

DECLARE @aName varchar(50), @aDesc varchar(50)
SET @aName = 'Lathed'
SET @aDesc = 'The tube has been lathed to size'

EXECUTE AddCondition @aName, @aDesc
GO
Run Code Online (Sandbox Code Playgroud)

但我一直收到错误:

消息245,级别16,状态1,过程AddCondition,第51
行将varchar值'Lathed'转换为数据类型int时转换失败.

在处理int和float值时,同样的过程也有效,所以我不确定我在这里缺少什么.我正在使用带有SQL Server Express的SQL Server 2014 Management Studio.

提前致谢!

Jam*_*iec 5

从您发布的代码中,只有一件事会产生您指定的错误,即[Condition Name]表中的列[dbo].[Tube Conditions]是int类型,而不是insert语句所期望的varchar.

顺便说一句:这是一种非常危险的方法来生成表中的下一个ID - 当同时插入2条记录时,它会引发并发问题.SQL将为您生成此标识,查找它.