我有一个以下列形式返回数据的查询
attribute value
--------- ----------
petid 1000
name buttercup
species cat
age 10
owner Bob Dole
基本上我想要遍历每一行并在一个字符串中返回字段名称和种类,所以结果将是
buttercup cat
我有什么想法可以做到这一点?
答案 0 :(得分:3)
试试这个。我只尝试过使用SQL Server 2008,但它可能会起作用:
DECLARE @Concat nvarchar(50)
SET @Concat=N''
SELECT @Concat = @Concat + Value + N' '
FROM dbo.AttributeValue
WHERE Attribute IN (N'name', N'species')
SELECT @Concat
答案 1 :(得分:2)
好的 - 现在我想我理解数据格式......
以下是创建示例集的代码(只是为了确保我做对了)
CREATE TABLE MyTable
(
attribute varchar(20),
value varchar(20)
)
INSERT INTO MyTable VALUES('petid','1000')
INSERT INTO MyTable VALUES('name','buttercup')
INSERT INTO MyTable VALUES('species','cat')
INSERT INTO MyTable VALUES('age','10')
INSERT INTO MyTable VALUES('owner','Bob Dole')
以下是我的回答:
SELECT a.value + ' ' +b.value
FROM MyTable AS a
INNER JOIN MyTable AS b ON a.attribute='name' AND b.attribute = 'species'
答案 2 :(得分:1)
执行此操作的光标方式可能是这样的 -
DECLARE @name varchar(20)
DECLARE @species varchar(20)
DECLARE nameSpeciesCursor CURSOR FOR
SELECT name, species FROM tableName
OPEN nameSpeciesCursor
FETCH NEXT FROM nameSpeciesCursor INTO @name, @species
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @name + ' ' + @species
FETCH NEXT FROM nameSpeciesCursor INTO @name, @species
END
CLOSE nameSpeciesCursor
DEALLOCATE nameSpeciesCursor
欢呼声