SQLTeam.com | Weblogs | Forums

Select query

Hi need help here with select query

cur = conn.cursor()
sql = "select Name, Age, City from data;"
cur.execute(sql)

can a variable be used to store (Name, Age, City)

variable= (Name, Age, City)
sql = "select variable from data;"

Thx.

Your solution should look like this:

--declare your variables`
DECLARE 
    @name VARCHAR(50), 
    @Age   INT,
    @City VARCHAR(50);

--declare your cursor with a name
DECLARE your_cursor_name CURSOR
FOR SELECT name, age, city FROM dbo.data

--get the data set for the cursor
OPEN your_cursor_name ;

 --traverse the data set one by one and store the retrieved data into variables
FETCH NEXT FROM your_cursor_name INTO 
    @name VARCHAR(50), 
    @Age   INT,
    @City VARCHAR(50);
 
-- for as long as the data set is not empty, loop
WHILE @@FETCH_STATUS = 0
    BEGIN
    -- do the cool things you want to do with the data, like print
    --  "The 30 year old Larry is looking for love in New York." 
        PRINT 'The ' + CAST(@Age as varchar(10)à + ' year old ' + @name + ' is looking for love in ' + @City + '.' ;

        --get the next line form the data set
        FETCH NEXT FROM your_cursor_name INTO 
             @name VARCHAR(50), 
             @Age   INT,
             @City VARCHAR(50);
 
    END;

--After that, close the cursor.
CLOSE your_cursor_name ;

--Finally, deallocate the cursor to release it.
DEALLOCATE your_cursor_name ;

So, no, you can not store all the different attributes in one variable. You need to define a separate variable (and its type) for each attribute you retrieve with the cursor.

Hope this helps.

1 Like

I found some errors in my previous post, last part of the script should be.

FETCH NEXT FROM your_cursor_name INTO 
    @name, 
    @Age
    @City;
 
-- for as long as the data set is not empty, loop
WHILE @@FETCH_STATUS = 0
    BEGIN
    -- do the cool things you want to do with the data, like print
    --  "The 30 year old Larry is looking for love in New York." 
        PRINT 'The ' + CAST(@Age as varchar(10)) + ' year old ' + @name + ' is looking for love in ' + @City + '.' ;

        --get the next line form the data set
        FETCH NEXT FROM your_cursor_name INTO 
             @name, 
             @Age,
             @City;
 
    END;

What is your end goal, what are you attempting to do with the sample query result? Display it on a report or display it to a use through a form or a web application or .....