我有下表:
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 客户端 11.0][SQL Server]转换日期和/或时转换失败 来自字符串的时间。
我已经检查过,以下行返回一个整数:
':userid' => intval($row['UserId']),
鉴于我的第二列是瓦尔查尔,好吧,我很困惑。为什么当我根本不使用日期并且传递整数值时会看到此错误?
您的列Created
的类型为日期时间,并且您使用 Varchar 作为默认值。
ALTER TABLE [dbo].[UserSession] ADD DEFAULT (user_name()) FOR [Created]
看起来你反转了创建者和创建者。
您是否指定了日期格式?
Select CONVERT(Date, '17-9-2013', 105)
105 代表 (日-月-年)。
请参考 http://msdn.microsoft.com/en-us/library/ms187928.aspx