SQL varchar vs varchar(n)

【标题】:SQL varchar varchar(n)
【日期】:2016-07-04
【类别】:SQLSERVER
【问题】:T-SQL 声明变量类型为varchar后执行插入语句插入不成功
【原因】:声明变量varchar不带长度,sqlserver会默认长度1代替
http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/09/bad-habits-to-kick-declaring-varchar-without-length.aspx
【怎么发现的】:

declare @f_accounts varchar
set @f_accounts='H6155'

MERGE INTO t_OtherCredit AS T
using (SELECT @f_accounts AS f_accounts) AS S
ON (T.f_accounts = S.f_accounts AND Datediff(d, T.f_date, Getdate()) = 0)
WHEN NOT MATCHED THEN
INSERT (f_accounts,
f_date)
VALUES(@f_accounts,
Getdate()) ;
--执行T-SQL后查询
SELECT *
FROM t_OtherCredit
WHERE Datediff(d, f_date, Getdate()) = 0
AND f_accounts = 'H6154'

无数据,然而,直接替换@f_accounts为字面量查询到正常数据

【修复】:declare @f_accounts varchar(20)

【在哪些文件修改了】: 无

【我导致的】:是

【解决Bug的时间】:2016-07-04 13:10

【教训】:sqlserver还是简单了解阶段

posted @ 2016-07-04 14:47  楊柳  阅读(555)  评论(0编辑  收藏  举报