【问题标题】:Inserting DateTime into datetime field TSQL将日期时间插入日期时间字段 SQL
【发布时间】:2013-10-17 12:12:35
【问题描述】:

我正在尝试从 C# 程序调用 SQL Server 2012 Express 中的存储过程,以将 DateTime 数据类型插入列(也是日期时间)。

由于某种原因,我不断收到有关“从字符串转换日期和/或时间时对话失败”的错误消息。

我检查了我的 SQL 服务器中的文化设置,设置为 us_english,但日期时间格式是 ISO 标准。

这是存储过程中的代码。这些值正是 C# 应用程序传递它们的方式。

USE testdb;
DECLARE @Name NVARCHAR(50) = 'Somename', 
    @Location NVARCHAR(50) = 'somelocation',
    @Date DateTime = '2013-10-11 11:00:05.000'

BEGIN

SET NOCOUNT ON;

SELECT @Name, @Location, @Date

if exists (select name from ComputerHistory where name = @Name)
    begin
        DECLARE @Query1 NVARCHAR(MAX)
        if @Location <> 'disconnected'
            begin
                set @Query1 = '
                    update ComputerHistory 
                    set ' + @Location + ' = 1 + ISNULL((select MAX(' + @Location + ') from ComputerHistory where name = ''' + @Name + '''),0),
                    lastdateonline = ''' + @Date + '''
                    where name = ''' + @Name + '''
                    '

                --EXEC sp_executesql @Query1
            end
        else
            begin
                set @Query1 = '
                    update ComputerHistory 
                    set ' + @Location + ' = 1 + ISNULL((select MAX(' + @Location + ') from ComputerHistory where name = ''' + @Name + '''),0)
                    where name = ''' + @Name + '''
                    '
                EXEC sp_executesql @Query1
            end
    end
else
    begin
        DECLARE @Query2 NVARCHAR(150)
        set @Query2 = 'insert into ComputerHistory(name, ' + @Location + ') VALUES(''' + @Name + ''', ''1'')'
        EXEC sp_executesql @Query2
    end
END

【问题讨论】:

    标签: tsql sql-server-2012-express


    【解决方案1】:

    尝试强制转换(@Date as nvarchar(50))

                    set @Query1 = '
                    update ComputerHistory 
                    set ' + @Location + ' = 1 + ISNULL((select MAX(' + @Location + ') from ComputerHistory where name = ''' + @Name + '''),0),
                    lastdateonline = ''' + cast(@Date as nvarchar(50)) + '''
                    where name = ''' + @Name + '''
                    '
    

    【讨论】:

    • 应该可以。看起来 SQL Server 没有在隐式转换中应用正确的类型。代码 declare @date datetime = '2013-10-11 11:00:05.000'; select 'Date is: ' + @date 不起作用,而 declare @date datetime = '2013-10-11 11:00:05.000'; select 'Date is: ' + convert(nchar(25), @date) 起作用。
    • 谢谢!像魅力一样工作!
    • 这段代码正在构建一个字符串(用于动态 SQL)。每当 sql 组合不同的数据类型时,它都会使用数据类型优先级来做到这一点。此处的文档:technet.microsoft.com/en-us/library/ms190309.aspx 在这种情况下,有一个字符串和一个日期时间。 SQL 尝试将字符串转换为日期时间,而不是相反。
    猜你喜欢
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 2013-05-19
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多