在SQL中将Text转换为INT

时间:2016-12-06 20:33:49

标签: sql-server stored-procedures

sm_ValueTEXT列,我需要将其转换为INT

事实上只有两个人会弄乱这个表,这个列将是数字的(幽默我)

我收到此错误消息:

  

Msg 206,Level 16,State 2,Procedure User_Password_Date_Interval_Check,Line 10
  操作数类型冲突:文本与int

不兼容

我试过了:

SELECT CONVERT(INT, sm_Value)) 
FROM Setting_Misc

但我仍然得到错误。

IF EXISTS (SELECT * FROM sysobjects 
           WHERE type = 'P' AND name = 'User_Password_Date_Interval_Check')
BEGIN
    PRINT 'Dropping Procedure User_Password_Date_Interval_Check'
    DROP  Procedure  User_Password_Date_Interval_Check
END
GO

PRINT 'Creating Procedure User_Password_Date_Interval_Check'
GO

CREATE Procedure User_Password_Date_Interval_Check
    @ua_pk uniqueidentifier
AS
    DECLARE @PasswordExpireDays INT

    SELECT 
        CONVERT(INT, CONVERT(VARCHAR(MAX), sm_Value)) 
    FROM Setting_Misc

    SELECT
        @PasswordExpireDays = COALESCE(sm_Value,0)
    FROM
        Setting_Misc AS sm
    INNER JOIN
        Syndicates As syn ON sm.syn_fk = syn.syn_pk
    INNER JOIN
        Company As c ON c.syn_fk = syn.syn_pk
    INNER JOIN
        User_Accounts As ua ON ua.c_fk = c.c_pk
    WHERE 
        sm.sm_Setting = 'PasswordExpireDays'
GO

GRANT EXEC ON User_Password_Date_Interval_Check TO WEB

1 个答案:

答案 0 :(得分:1)

您必须在设置变量的位置进行转换。

IF EXISTS (SELECT * FROM sysobjects 
           WHERE type = 'P' AND name = 'User_Password_Date_Interval_Check')
BEGIN
    PRINT 'Dropping Procedure User_Password_Date_Interval_Check'
    DROP  Procedure  User_Password_Date_Interval_Check
END
GO

PRINT 'Creating Procedure User_Password_Date_Interval_Check'
GO

CREATE Procedure User_Password_Date_Interval_Check
    @ua_pk uniqueidentifier
AS
    DECLARE @PasswordExpireDays INT
    --This conversion doesn't cascade down to the next SELECT statement
    SELECT 
        CONVERT(INT, CONVERT(VARCHAR(MAX), sm_Value)) 
    FROM Setting_Misc

    SELECT
        --Here is what has to change
        --@PasswordExpireDays = COALESCE(sm_Value,0)
          @PasswordExpireDays = CONVERT(INT, CONVERT(VARCHAR(MAX), sm_Value)) 
    FROM
        Setting_Misc AS sm
    INNER JOIN
        Syndicates As syn ON sm.syn_fk = syn.syn_pk
    INNER JOIN
        Company As c ON c.syn_fk = syn.syn_pk
    INNER JOIN
        User_Accounts As ua ON ua.c_fk = c.c_pk
    WHERE 
        sm.sm_Setting = 'PasswordExpireDays'
GO

GRANT EXEC ON User_Password_Date_Interval_Check TO WEB