1

我正在尝试从 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
4

1 回答 1

1

试试 cast(@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 + '''
                '
于 2013-10-17T12:29:52.707 回答