我尝试编写一个接受两个输入(内容ID和内容类型)的SQL查询,根据用户设置的内容类型从不同的源表填充临时表,然后最终运行对临时表的查询。我想我会把我的临时表合并到我的IF / ELSE语句中。
所以我的问题是,为什么这会返回一些非零数字的结果:
DECLARE @contentID int, @contenttype varchar
SET @contentid = 28861
SET @contenttype = 'resource'
DECLARE @tags_current TABLE (contentID int, taxonomyID int, isPrimary int)
INSERT INTO @tags_current (contentID, taxonomyID, isPrimary)
SELECT resourceID as contentID, taxonomyID, isPrimary
FROM resource2taxonomy r2t
WHERE r2t.resourceID = @contentID
SELECT * FROM @tags_current
然而这会返回零结果:
DECLARE @contentID int, @contenttype varchar
SET @contentid = 28861
SET @contenttype = 'resource'
DECLARE @tags_current TABLE (contentID int, taxonomyID int, isPrimary int)
IF (@contenttype = 'resource')
BEGIN
INSERT INTO @tags_current (contentID, taxonomyID, isPrimary)
SELECT resourceID as contentID, taxonomyID, isPrimary
FROM resource2taxonomy r2t
WHERE r2t.resourceID = @contentID
END
SELECT * FROM @tags_current
另外,我已经尝试了这个,它也会返回零结果:
DECLARE @contentID int, @contenttype varchar, @command varchar
SET @contentid = 28861
SET @contenttype = 'resource'
DECLARE @tags_current TABLE (contentID int, taxonomyID int, isPrimary int)
IF (@contenttype = 'resource')
BEGIN
SET @command = 'INTO @tags_current (contentID, taxonomyID, isPrimary) SELECT resourceID as contentID, taxonomyID, isPrimary FROM resource2taxonomy r2t WHERE r2t.resourceID = @contentID'
END
EXECUTE(@command)
SELECT * FROM @tags_current
我已经阅读了this,this和this,但由于某种原因,它只是没有点击我。我使用的是MS SQL Server 2014,如果有帮助的话。这是SQL Fiddle。谢谢!
答案 0 :(得分:5)
这实际上非常简单,你没有给@contenttype
一个长度,因此,默认情况下它的长度为1个字符。
如果你这样做,这将很清楚:
DECLARE @contentID int, @contenttype varchar
SET @contentid = 28861
SET @contenttype = 'resource'
SELECT @contenttype
结果为r
,因此,IF (@contenttype = 'resource')
不正确