1

我写了一个像下面这样的游标:

declare myCursor cursor 
for select productID, productName from products
declare @productID int 
declare @productName nvarchar(50)

open myCursor
fetch next from myCursor into @productID,@productName
print @productID
print @productName
set @productID=0
set @productName=''

while @@FETCH_STATUS=0
begin
    fetch next from myCursor into @productID,@productName
    print @productID
    print @productName
    set @productID=0
    set @productName=''
end
close myCursor
deallocate myCursor

现在它在彼此下方打印产品的 ID 和名称,例如:

1
Coffee
2
Apple …

但我想将每个产品的 ID 和名称放在同一行中,例如:

1   coffee
2   apple  …

我能做些什么?我将 id 转换为 String 并使用 +''+ 将 id 和 name 连接到同一个字符串中。但是由于 ids 和 names 的长度不同,所以结果不干净。有没有其他方法可以做到这一点?

4

6 回答 6

2

尝试使用 TAB

print convert(nvarchar(30),@productID) + char(9) + @productName

或使用 NCHAR

print convert(nvarchar(8),@productID) +  @productName
于 2010-08-24T11:29:30.510 回答
1

取决于您的电话号码可以是多长时间:

print convert(char(10), @productID) + ' ' + @productName

Char 将用额外的空格右填充数字,为您提供固定的数字。

于 2010-08-24T11:30:47.160 回答
1

一开始你可以确定最长数字的长度

DECLARE @length INT

SELECT @length = CAST(LOG10(MAX(productID)) AS INT)+1 FROM products

然后将其合并到您的打印语句中,例如

PRINT LEFT(CAST(@productID AS VARCHAR(10)) + 
    SPACE(@length),@length) + ' ' + @productName

为此,我只会在 SSMS 中使用“结果作为文本”而不​​是光标。希望这只是一个学习练习!

于 2010-08-24T11:38:02.367 回答
0

我想更简单的解决方案是在客户端应用程序中定义格式化规则,但如果你真的需要在数据库中使用它,这很简单,为什么要在你的解决方案中使用游标:

SELECT left(convert(varchar(20), productID) + '      ',6) + ' - ' + productName
from products
于 2010-08-24T11:37:01.430 回答
0

您可以使用这样的表格,而不是使用游标...

DECLARE @products TABLE (ProductID int, ProductName nvarchar(50), RowIndex int IDENTITY(1,1))

INSERT INTO @products (ProductID, ProductName) SELECT ProductID, ProductName FROM products

DECLARE @totalRows int
DECLARE @rowIndex int

SELECT 
    @totalRows = COUNT(RowIndex), 
    @rowIndex = 1 
FROM @products

DECLARE @ProductID int
DECLARE @ProductName nvarchar(50)

WHILE(@rowIndex < @totalRows)
BEGIN

    SELECT @ProductID = ProductID, @ProductName = ProductName FROM @products WHERE RowIndex = @rowIndex

    -- Do here your stuff...
    PRINT LEFT(CAST(@productID as varchar) + '      ',6) + ' - ' + @productName 

    SET @rowIndex = @rowIndex + 1   

END
于 2010-08-24T11:39:46.407 回答
0

为什么要使用游标进行简单的提取……它非常慢,一次只能处理一行!不惜一切代价远离游标!

您可以使用简单的 select 语句将它们都检索为新列。

select convert(nvarchar(5),productID) + ' ' + productName as 'ID_Name' from products

第一部分选择产品 ID 作为字符串。然后它包含一个“空格”(“”),然后将产品名称连接到它的末尾。

你最终会得到

1 苹果

2 香蕉

等等等等,它会比你当前的光标快 1000 倍

希望有帮助,

韦斯

于 2010-08-24T11:46:05.047 回答