开发者

SQL Cursor/Population Question

开发者 https://www.devze.com 2023-01-08 18:33 出处:网络
So here\'s the setup. I have two tables: CREATE TABLE dbo.TmpFeesToRules1(Name varchar, LookupId int) CREATE TABLE dbo.TempFeesToRules2(FeeId int, Name varchar)

So here's the setup. I have two tables:

CREATE TABLE dbo.TmpFeesToRules1(Name varchar, LookupId int)
CREATE TABLE dbo.TempFeesToRules2(FeeId int, Name varchar)

I have a third table called 'Fee' in the database that's already created. I want to populate dbo.TmpFeesToRules1 'Name' field with the DISTINCT 'Name' from 'Fee开发者_Python百科'. Would I do this like this?

INSERT INTO dbo.TmpFeesToRules1(Name, LookupId)
VALUES (SELECT DISTINCT Name FROM Fee, 0)

Then I want to use a cursor to loop through dbo.TmpFeesToRules1 and insert each of these rows into another table called 'Lookup', so those names would then have LookupId's assigned to them:

DECLARE db_cursor CURSOR FOR  
SELECT Name 
FROM dbo.TmpFeesToRules1 

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @Name   

WHILE @@FETCH_STATUS = 0   
BEGIN   
       INSERT INTO dbo.Lookup (LookupType, LookupDesc)
       VALUES ('FEE', @Name)

       FETCH NEXT FROM db_cursor INTO @name   
END   

CLOSE db_cursor

Then I want to come back to dbo.TmpFeesToRules1 and UPDATE it and insert those LookupId's for each one of the names. How do I do this?

Also, I don't think my SQL is entirely correct for everything else either? Can you guys verify this?


Why on earth would you do this in a cursor?

http://wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them


Instead of mucking about with cursors, I would just do the following:

INSERT INTO dbo.TmpFeesToRules1 (name, LookupId)
SELECT DISTINCT name, 0 FROM Fee

INSERT INTO Lookup (LookupType, LookupDesc)
SELECT 'FEE', name FROM dbo.TmpFeesToRules1

UPDATE TFTR
SET
    LookupID = LU.id
FROM
    Lookup LU
INNER JOIN dbo.TmpFeesToRules1 TFTR ON
    TFTR.name = LU.LookupDesc
WHERE
    LU.LookupType = 'FEE'

There are a lot of assumptions made here - for example that other FEE lookups with the same description don't already exist.

There seemed to be a lot of problems with your SQL syntax as well as your strategy here. If this is for a production system I strongly suggest that you find a SQL developer who know what he's doing to handle these kinds of things.


No cursors needed.

For your first question (inserting into TmpFeesToRules1)

INSERT INTO dbo.TmpFeesToRules1(Name, LookupId)
SELECT DISTINCT Name, 0 FROM Fee

For your second question (insert into Lookup):

INSERT INTO Lookup (LookupType, LookupDesc)
SELECT 'FEE', Name
FROM dbo.TmpFeesToRules1

For your third question, is there any primary key in Lookup or TmpFeesToRules1?

0

精彩评论

暂无评论...
验证码 换一张
取 消