将DateTime插入datetime字段SQL

时间:2013-10-17 12:12:35

标签: tsql sql-server-2012-express

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

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

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

这是存储过程的代码。这些值正是它们通过C#app传递的方式。

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

1 个答案:

答案 0 :(得分: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 + '''
                '