0

我有下表:

USE [junglegymSQL]
GO

ALTER TABLE [dbo].[UserSession] DROP CONSTRAINT [FK_UserSession_UserID]
GO

ALTER TABLE [dbo].[UserSession] DROP CONSTRAINT [DF__UserSessi__Creat__5CA1C101]
GO

ALTER TABLE [dbo].[UserSession] DROP CONSTRAINT [DF__UserSessi__Creat__5BAD9CC8]
GO

/****** Object:  Table [dbo].[UserSession]    Script Date: 16/09/2013 3:44:55 PM ******/
DROP TABLE [dbo].[UserSession]
GO

/****** Object:  Table [dbo].[UserSession]    Script Date: 16/09/2013 3:44:55 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[UserSession](
    [UserId] [int] NOT NULL,
    [SessionId] [varchar](500) NOT NULL,
    [Created] [datetime] NOT NULL,
    [CreatedBy] [varchar](50) NOT NULL,
    [LastModifed] [datetime] NULL,
    [LastModifiedBy] [varchar](50) NULL,
 CONSTRAINT [PK_SessionID] PRIMARY KEY CLUSTERED 
(
    [SessionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[UserSession] ADD  DEFAULT (user_name()) FOR [Created]
GO

ALTER TABLE [dbo].[UserSession] ADD  DEFAULT (getdate()) FOR [CreatedBy]
GO

ALTER TABLE [dbo].[UserSession]  WITH CHECK ADD  CONSTRAINT [FK_UserSession_UserID] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([UserId])
GO

ALTER TABLE [dbo].[UserSession] CHECK CONSTRAINT [FK_UserSession_UserID]
GO

我正在尝试使用以下 PHP 编写:

$sessiontoken = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));

// Save our cookie 'qcore' with the users session id
setcookie("qcore", $sessiontoken);

$query = "
    INSERT INTO dbo.UserSession ( 
        UserId ,
        SessionId
    ) VALUES  (
        :userid ,
        :sessionid  
    )
";

$query_params = array( 
    ':userid' => intval($row['UserId']), 
    ':sessionid' => $sessiontoken 
); 

try 
{ 
    // Execute the query to create the user 
    $stmt = $db->prepare($query); 
    $result = $stmt->execute($query_params); 
} 
catch(PDOException $ex) 
{ 
    // Note: On a production website, you should not output $ex->getMessage(). 
    // It may provide an attacker with helpful information about your code.  
    // die("Failed to run query: " . $ex->getMessage()); 
    die("Failed to run query: " . $ex->getMessage()); 
} 

但是,每次我这样做时,都会收到以下错误:

无法运行查询:SQLSTATE[22007]:[Microsoft][SQL Server Native Client 11.0][SQL Server]从字符串转换日期和/或时间时转换失败。

我已经检查过了,以下行返回一个整数:

':userid' => intval($row['UserId']), 

鉴于我的第二列是 varchar,好吧,我很困惑。当我根本不使用日期并且我正在传递一个整数值时,为什么会看到这个错误?

4

2 回答 2

2

您的列Created是 datetime 类型,并且您使用 Varchar 作为默认值。

ALTER TABLE [dbo].[UserSession] ADD  DEFAULT (user_name()) FOR [Created]

看起来你颠倒了 Created 和 CreatedBy。

于 2013-09-16T06:00:48.910 回答
0

你指定日期格式了吗??

Select CONVERT(Date, '17-9-2013', 105)

105代表(dd-mm-yyyy )。

请参考http://msdn.microsoft.com/en-us/library/ms187928.aspx

于 2013-09-16T05:57:35.167 回答