简体   繁体   English

在SQL Server中将datetime转换为字符串/ varchar

[英]Convert datetime to string/varchar in SQL Server

I have a view in SQL Server which uses dates to determine which tables to access data from. 我在SQL Server中有一个视图,该视图使用日期来确定从哪些表访问数据。 The problem is it only seems to work when given the date as a varchar like '20120423' . 问题在于,仅当给定日期为'20120423'这样的varchar时,它才似乎有效。

So I am trying to dynamically create this date with GETDATE() instead of having to use the typed out version. 因此,我尝试使用GETDATE()动态创建此日期,而不是必须使用键入的版本。 When I run the top SELECT statement it returns '20120423' like I would expect but when I try to compare the two values they are not equal and the IF statement prints 'VALUES ARE NOT THE SAME' . 当我运行顶部的SELECT语句时,它会像我期望'20120423'那样返回'20120423'但是当我尝试比较两个值时,它们不相等,并且IF语句显示'VALUES ARE NOT THE SAME'

SELECT 
    '''' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +'''' 

IF '''' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''''  = '20120423' 
BEGIN
    PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
   PRINT 'VALUES ARE NOT THE SAME'
END

I'm kind of lost as to where to go from here. 我对从这里去哪里有些迷茫。 Thanks for any help. 谢谢你的帮助。

EDIT : 编辑
With the answers given then these two queries should be the same even though they are treated differently by my view. 给出答案后,即使我认为对这两个查询的处理方式有所不同,这两个查询也应该相同。

SELECT * 
FROM DatesView 
WHERE Timestamp > CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)

SELECT * 
FROM DatesView 
WHERE Timestamp > '20120423'

The top one looks through all tables where the bottom one correctly only searches the necessary tables. 顶部的浏览所有表,而底部的仅正确搜索必要的表。

You're getting thrown off by the quote marks, just remove them they are unnecessary. 您会被引号抛弃,只需删除它们就可以了。

SELECT CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) 

IF CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)  = '20120423' 
BEGIN
    PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
   PRINT 'VALUES ARE NOT THE SAME'
END

Delete the first two ' . 删除前两个' Try this. 尝试这个。 You are comparing '20120423'=20120423 您正在比较'20120423'=20120423

SELECT '' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +'' 

IF '' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''  = '20120423' 
BEGIN
    PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
   PRINT 'VALUES ARE NOT THE SAME'
END

You are adding apostrophes to the string, so your comparison is literally (replacing the string delimiters with brackets): 您将在字符串中添加撇号,因此您的比较从字面上看 (用括号替换字符串定界符):

if ['20120423']  = [20120423]   

I think you want: 我想你要:

IF CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) = '20120423'

and/or 和/或

SELECT CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM