![](/img/trans.png)
[英]Conversion failed when converting date and/or time from character string when converting inputted time | SQL, SQLSRV
[英]Conversion failed when converting date and/or time from character string - but no idea why
我有下表:
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,好吧,我很困惑。 當我根本不使用日期並且傳遞整數值時,為什么會看到此錯誤?
您Created
列是datetime類型,並且您使用Varchar作為默認值。
ALTER TABLE [dbo].[UserSession] ADD DEFAULT (user_name()) FOR [Created]
看起來你扭轉了Created和CreatedBy。
你有沒有指定日期格式?
Select CONVERT(Date, '17-9-2013', 105)
105代表(dd-mm-yyyy )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.