Showing posts with label record. Show all posts
Showing posts with label record. Show all posts

Friday, March 30, 2012

How to insert records into two tables that references each other?

I have two tables , A1 and B1 . B1 has a reference key pointing to A1.ID which is a primary key. Now I want to INSERT a record into both table.

CREATE TABLE a1 (
T_ID INTEGER IDENTITY(1,1) PRIMARY KEY,
T_Test INTEGER NOT NULL,
);

CREATE TABLE B1 (
B_ID INTEGER IDENTITY(1,1) PRIMARY KEY,
T_SID INTEGER NOT NULL REFERENCES a1(T_ID),
);

-- A function to get the next primary key value

-- Get the next unique key from A1
CREATE FUNCTION [dbo].[getTicketNo]
(
)
RETURNS INT
AS
BEGIN
RETURN (SELECT Max(T_ID) from A1)
END

I can only insert a record into a table at a time. and I rely on dbo.getTicketNo() to get the lastest T_ID

I wonder how do you insert a new record into A1 and B1 and maintain referential integrity? You must call Insert twice to accomplish the job right?

What I want to insert a record into B1.SID is the primary key value (T_ID) that was created during "Insert into A1 values (0)", using dbo.getTicketNo()
I worry if I am going to insert a record into A1 first, then insert a record into B1 next, there is a chance the data wont be consistent; as I illustrated a situation below:

t A1 B1
0 (0)Insert
1 (1)Insert
2 (0)Insert
3 (1)Insert

dbo.getTicketNo() at t3 may return the wrong value if another process (1)insert is executed, that will change the primary key number to 2 which is incorrect

Can I lock up A1 and then unlock A1 after I finished working with B1?

If so, what would happen to the application if it tries to access into A1 during it is locked?

If you ask me this not a good approach to get the identity value.
You can use the following objects to get the last inserted identity value.

@.@.Identity or Scope_Identity()

1.Insert the data on Master table (A1)
2.Then get the last inserted value from those system functions or global varibale
3.Use the values on Child table (B1)

Example,

Insert into A1(T_Test) values (@.T_Test);
Insert into B1(T_SID) values (@.@.Identity)
--or
Insert into B1(T_SID) values (Scope_Identity())

NOTE: Don't use MAX function to get the last inserted identity value. It may be
Inserted by other concurrent users.

|||


Thank you ManiD

From your code, is there any chance that another INSERT query is executed by other concurrent users after the 1st Insert and before the 2nd Insert in your case?

time 0:00:00 (User 0) Insert into A1(T_Test) values (@.T_Test);
time 0:00:20 (User 1) Insert into A1(T_Test) values (@.T_Test);
time 0:00:21 (User 0) Insert into B1(T_SID) values (@.@.Identity)

If it is possible, what is the best approach to ensure that the second Insert into B1 is consistent to the master A1?

Thanks for your precious time

|||

In this case,

@.@.Identity hold the User1 Identity data..

So it always good idea to use SCOPE_IDENTITY() instead of using @.@.Identity..

SCOPE_IDENTITY always hold the current user's identity data...

|||

Ok,,, thank you ManiD

Let me do some research on SCOPE_Indentity() ...

Thank you for your kind replies

|||

When I google it, found some people mispelled SCOPE_IDENTITY() to SCOPE_INDENTITY() .....

Here is the MSDN for SCOPE_IDENTITY() if anyone got the similar issues can have a look

http://msdn2.microsoft.com/en-us/library/ms190315.aspx

How to insert record to SQL server which is on the other machine from client computer?

I want to write simple sql database project that that works in the network. and i need to insert record from a client to a server that is on the other machine.

This is a pretty broad question. I suggest you do some additional research online or via any one of a number of excellent books, articles or whitepapers.

This will require that you (at least)

Install and configure the SQL Server on the remote system.

how to insert multiple records into table

insert into table1 (colname) values (value1)

can only insert one record into the table. How to insert multiple records as value1, value2, value3... into a table?

We can of course use the above repeatedly, but if I don't know how many records (which is a variable), and I want to write a code which just take

value1, value2, value3 ...

from the clipboard, to paste as a input. How to insert those multiple records into table without split it. Thanks

What is the source of the data? from another table?

|||

If you are taking values from another table then you can insert multiple records.

Any ways i think it internally dosen't make much difference if you use multiple records or single record multiply internall it will fire that many insert statements only.

I find this intresting article guess it will help

http://blog.sqlauthority.com/2007/06/08/sql-server-insert-multiple-records-using-one-insert-statement-use-of-union-all/

|||

U want place into the same table r other clarity is required

Insert into x select * from x

insert into x select * from y

If u want to copy the data of entire table use * other wise U have to specify column clause

Thank u

Baba

Please remember to click "Mark as Answer" on this post if it helped you.

|||

I hope I'm getting your question right.

Are you looking for something like

insert into table1 ( colname )
select value1 union all
select value2 union all
.
.
.
select valueN

If you can specify your problem in details then we can help you better.

|||

Thank everyone for your input. What I want was taking the contents of multiple records delimited by delimiter from clipboard as a string, then insert into a table. I complished by writing a user function which takes a string, then output a table with multiple records, it works as

insert into table1 (ID)

select values from fn_StringToTable(@.myString, @.delimiter) -- here @.myString='00a1,00a2,00a3,...'; @.delimiter=','

output table1 got the IDs from the clipboard which has'00a1,00a2,00a3,...

Thanks

How to insert into a table with a function?

I want to add a record into a table, using a function.

This function needs to give back the number of records of a given table.

Function ImportResults

@.NumberOfRecords int

@.TableName varchar(60)

@.ImportDate datetime

@.Result bit

@.Result = 1

@.ImportDate =getdate()

--Open Table with tablenames

select TableName from Tbl_ImportTables

For each record in Tbl_ImportTables

@.TableName = Tbl_ImportTables.TableName

@.NumberOfRecords = select count(*) from @.TableName

-- add to Import Results

Insert into Tbl_Import_Results

(ImportDate

,TableName

,NumberOfRecords

)

VALUES

(

@.ImportDate

, @.TableName

, @.NumberOfRecords

)

-- Check 0 records (I only want to know if there is a table with 0 records)

IF @.NumberOfRecords=0 then @.Result=0

Next record

RETURN @.Result

End function

Can somebody help me with the right syntax (I am new to functions and sp's)?

Is this a scalar valued function?

Thanks,

Frans

DML operations (except local table variables) are not allowed in SQL Functions, you will have to use a stored procedure for that.

Jens K. Suessmeyer

http://www.sqlserver2005.de

|||Yes, this is really a stored procedure.

As you are dynamically selecting the tablename you may want to look at the following topics in Books Online:

1) Cursors - to replace your For Each Loop
2) EXEC or sp_executesql - to dynamically execute a sql string built.

You may want to consider inserting the importdate and tablename first and then just updating the numberofrecords value in your cursor:

ie INSERT INTO Tbl_Import_Results (ImportDate, TableName) SELECT GETDATE(), TableName FROM tbl_ImportTables

HTH!

|||

OK,

I have started to built a basic function in which a sp is called.

ALTER FUNCTION [dbo].[fnImportResult]

RETURNS bit

AS

BEGIN

EXEC dbo.[TestInsert]

@.ControleDatum= '12-10-2007'

,@.BronDatabase = N'aaa'

,@.Tabelnaam = N'bbb'

,@.AantalRecords = 3333

RETURN 0

END

If I run this function I get the following message:

Only functions and extended stored procedures can be executed from within a function.

When only the EXEC part is run then no error message

What am I doing wrong?

Thanks again,

Frans

|||As the message indicates, you cannot call Stored Procedures from a UDF.

|||

OK, so no DML operation or calling a Stored Procedure are allowed in a user defined function. Get it now

Is it correct that a sp cannot return a result?

If so, how can I make it to work? I need to know if one of the records which has been inserted intoTbl_Import_Results has 0 records (for the right ImportDate).

Please advise how you would do this (headlines are fine).

Thanks,

Frans

|||

Stored Procedures can return a results set. They can also return values to indicate success or failure or some other integer value.

Check out OUTPUT parameters and Return Codes in Books Online.


Good Luck!

|||

Slowly I am getting there. The Fetch is working

Now syntax is the problem:

This works:

set @.NumberOfRecords = select count(*) from [1_Exact_DS].[dbo].artbst

But not this (Error converting data type varchar to bigint.)

declare @.TableName as varchar(110)

set @.TableName= '[1_Exact_DS].[dbo].artbst'

set @.NumberOfRecords = (select count(*) from @.TableName)

This is not allowed:

set @.NumberOfRecords = EXEC(select count(*) from @.TableName)

How can I take care that first the @.TableName is resolved and than the select string?

Thanks again,

Frans

|||

You need to dynamically build the sql string to use EXEC

EXEC('SELECT COUNT(*) FROM ' + @.TableName)

|||

Thanks for your quick response

This gives 'incorrect syntax' :

set @.NumberOfRecords = EXEC('select count(*) from ' + @.TableName)

The result of the EXEC should go into the variable @.NumberOfRecords. But how?

Thanks,

Frans

|||

In this case, you won't be able to use EXEC to set the result of a query to a variable. You can however use sp_executesql instead of EXEC:

Code Snippet

declare @.TableName varchar(110)
declare @.NumberOfRecords int
declare @.sql nvarchar(200)

set @.TableName = 'dbo.sysobjects'

set @.sql = 'SELECT @.out = COUNT(*) FROM ' + @.TableName

exec sp_executesql @.SQL, N'@.out INT OUTPUT', @.NumberOfRecords output

select @.NumberOfRecords

HTH!

|||

This works great!!!! Exactly what I wanted

I even start to understand the syntax now.....

Thanks a lot for your help.

Frans

Wednesday, March 28, 2012

How to insert into a table with a function?

I want to add a record into a table, using a function.

This function needs to give back the number of records of a given table.

Function ImportResults

@.NumberOfRecords int

@.TableName varchar(60)

@.ImportDate datetime

@.Result bit

@.Result = 1

@.ImportDate =getdate()

--Open Table with tablenames

select TableName from Tbl_ImportTables

For each record in Tbl_ImportTables

@.TableName = Tbl_ImportTables.TableName

@.NumberOfRecords = select count(*) from @.TableName

-- add to Import Results

Insert into Tbl_Import_Results

(ImportDate

,TableName

,NumberOfRecords

)

VALUES

(

@.ImportDate

, @.TableName

, @.NumberOfRecords

)

-- Check 0 records (I only want to know if there is a table with 0 records)

IF @.NumberOfRecords=0 then @.Result=0

Next record

RETURN @.Result

End function

Can somebody help me with the right syntax (I am new to functions and sp's)?

Is this a scalar valued function?

Thanks,

Frans

DML operations (except local table variables) are not allowed in SQL Functions, you will have to use a stored procedure for that.

Jens K. Suessmeyer

http://www.sqlserver2005.de

|||Yes, this is really a stored procedure.

As you are dynamically selecting the tablename you may want to look at the following topics in Books Online:

1) Cursors - to replace your For Each Loop
2) EXEC or sp_executesql - to dynamically execute a sql string built.

You may want to consider inserting the importdate and tablename first and then just updating the numberofrecords value in your cursor:

ie INSERT INTO Tbl_Import_Results (ImportDate, TableName) SELECT GETDATE(), TableName FROM tbl_ImportTables

HTH!

|||

OK,

I have started to built a basic function in which a sp is called.

ALTER FUNCTION [dbo].[fnImportResult]

RETURNS bit

AS

BEGIN

EXEC dbo.[TestInsert]

@.ControleDatum= '12-10-2007'

,@.BronDatabase = N'aaa'

,@.Tabelnaam = N'bbb'

,@.AantalRecords = 3333

RETURN 0

END

If I run this function I get the following message:

Only functions and extended stored procedures can be executed from within a function.

When only the EXEC part is run then no error message

What am I doing wrong?

Thanks again,

Frans

|||As the message indicates, you cannot call Stored Procedures from a UDF.

|||

OK, so no DML operation or calling a Stored Procedure are allowed in a user defined function. Get it now

Is it correct that a sp cannot return a result?

If so, how can I make it to work? I need to know if one of the records which has been inserted intoTbl_Import_Results has 0 records (for the right ImportDate).

Please advise how you would do this (headlines are fine).

Thanks,

Frans

|||

Stored Procedures can return a results set. They can also return values to indicate success or failure or some other integer value.

Check out OUTPUT parameters and Return Codes in Books Online.


Good Luck!

|||

Slowly I am getting there. The Fetch is working

Now syntax is the problem:

This works:

set @.NumberOfRecords = select count(*) from [1_Exact_DS].[dbo].artbst

But not this (Error converting data type varchar to bigint.)

declare @.TableName as varchar(110)

set @.TableName= '[1_Exact_DS].[dbo].artbst'

set @.NumberOfRecords = (select count(*) from @.TableName)

This is not allowed:

set @.NumberOfRecords = EXEC(select count(*) from @.TableName)

How can I take care that first the @.TableName is resolved and than the select string?

Thanks again,

Frans

|||

You need to dynamically build the sql string to use EXEC

EXEC('SELECT COUNT(*) FROM ' + @.TableName)

|||

Thanks for your quick response

This gives 'incorrect syntax' :

set @.NumberOfRecords = EXEC('select count(*) from ' + @.TableName)

The result of the EXEC should go into the variable @.NumberOfRecords. But how?

Thanks,

Frans

|||

In this case, you won't be able to use EXEC to set the result of a query to a variable. You can however use sp_executesql instead of EXEC:

Code Snippet

declare @.TableName varchar(110)
declare @.NumberOfRecords int
declare @.sql nvarchar(200)

set @.TableName = 'dbo.sysobjects'

set @.sql = 'SELECT @.out = COUNT(*) FROM ' + @.TableName

exec sp_executesql @.SQL, N'@.out INT OUTPUT', @.NumberOfRecords output

select @.NumberOfRecords

HTH!

|||

This works great!!!! Exactly what I wanted

I even start to understand the syntax now.....

Thanks a lot for your help.

Frans

sql

How to insert into a table with a function?

I want to add a record into a table, using a function.

This function needs to give back the number of records of a given table.

Function ImportResults

@.NumberOfRecords int

@.TableName varchar(60)

@.ImportDate datetime

@.Result bit

@.Result = 1

@.ImportDate =getdate()

--Open Table with tablenames

select TableName from Tbl_ImportTables

For each record in Tbl_ImportTables

@.TableName = Tbl_ImportTables.TableName

@.NumberOfRecords = select count(*) from @.TableName

-- add to Import Results

Insert into Tbl_Import_Results

(ImportDate

,TableName

,NumberOfRecords

)

VALUES

(

@.ImportDate

, @.TableName

, @.NumberOfRecords

)

-- Check 0 records (I only want to know if there is a table with 0 records)

IF @.NumberOfRecords=0 then @.Result=0

Next record

RETURN @.Result

End function

Can somebody help me with the right syntax (I am new to functions and sp's)?

Is this a scalar valued function?

Thanks,

Frans

DML operations (except local table variables) are not allowed in SQL Functions, you will have to use a stored procedure for that.

Jens K. Suessmeyer

http://www.sqlserver2005.de

|||Yes, this is really a stored procedure.

As you are dynamically selecting the tablename you may want to look at the following topics in Books Online:

1) Cursors - to replace your For Each Loop
2) EXEC or sp_executesql - to dynamically execute a sql string built.

You may want to consider inserting the importdate and tablename first and then just updating the numberofrecords value in your cursor:

ie INSERT INTO Tbl_Import_Results (ImportDate, TableName) SELECT GETDATE(), TableName FROM tbl_ImportTables

HTH!

|||

OK,

I have started to built a basic function in which a sp is called.

ALTER FUNCTION [dbo].[fnImportResult]

RETURNS bit

AS

BEGIN

EXEC dbo.[TestInsert]

@.ControleDatum= '12-10-2007'

,@.BronDatabase = N'aaa'

,@.Tabelnaam = N'bbb'

,@.AantalRecords = 3333

RETURN 0

END

If I run this function I get the following message:

Only functions and extended stored procedures can be executed from within a function.

When only the EXEC part is run then no error message

What am I doing wrong?

Thanks again,

Frans

|||As the message indicates, you cannot call Stored Procedures from a UDF.

|||

OK, so no DML operation or calling a Stored Procedure are allowed in a user defined function. Get it now

Is it correct that a sp cannot return a result?

If so, how can I make it to work? I need to know if one of the records which has been inserted intoTbl_Import_Results has 0 records (for the right ImportDate).

Please advise how you would do this (headlines are fine).

Thanks,

Frans

|||

Stored Procedures can return a results set. They can also return values to indicate success or failure or some other integer value.

Check out OUTPUT parameters and Return Codes in Books Online.


Good Luck!

|||

Slowly I am getting there. The Fetch is working

Now syntax is the problem:

This works:

set @.NumberOfRecords = select count(*) from [1_Exact_DS].[dbo].artbst

But not this (Error converting data type varchar to bigint.)

declare @.TableName as varchar(110)

set @.TableName= '[1_Exact_DS].[dbo].artbst'

set @.NumberOfRecords = (select count(*) from @.TableName)

This is not allowed:

set @.NumberOfRecords = EXEC(select count(*) from @.TableName)

How can I take care that first the @.TableName is resolved and than the select string?

Thanks again,

Frans

|||

You need to dynamically build the sql string to use EXEC

EXEC('SELECT COUNT(*) FROM ' + @.TableName)

|||

Thanks for your quick response

This gives 'incorrect syntax' :

set @.NumberOfRecords = EXEC('select count(*) from ' + @.TableName)

The result of the EXEC should go into the variable @.NumberOfRecords. But how?

Thanks,

Frans

|||

In this case, you won't be able to use EXEC to set the result of a query to a variable. You can however use sp_executesql instead of EXEC:

Code Snippet

declare @.TableName varchar(110)
declare @.NumberOfRecords int
declare @.sql nvarchar(200)

set @.TableName = 'dbo.sysobjects'

set @.sql = 'SELECT @.out = COUNT(*) FROM ' + @.TableName

exec sp_executesql @.SQL, N'@.out INT OUTPUT', @.NumberOfRecords output

select @.NumberOfRecords

HTH!

|||

This works great!!!! Exactly what I wanted

I even start to understand the syntax now.....

Thanks a lot for your help.

Frans

how to insert data into to image datatype

i have a table gg. It has two fields one is ggno int, ggfig image .
how can i insert into the record into 'gg' table help me with examppleDepends on your coding language, there should be many exmaples out
there for each coding language. Normally you will need to open the
stream and fill a blob, but that is different in every coding language.

HTH, Jens Suessmeyer.

--
http://www.sqlserver2005.de
--

How to insert a zero length string into a field using SqlDataSource?

I have a few columns in table with default value defined as zero length string (''). I want to insert record from DetailsView which uses SqlDataSource as DataSource. In the ItemInserting event, if the data is not valid, I want to use zero length string for the column. But I always get Null instead of zero length string. The code in ItemInserting event looks like this:

If objddl.SelectedIndex > 0 Then
e.Values("myFld") = objddl.SelectedItem.Value
Else
e.Values("myFld") = ""
End If

The line: e.Values("myFld") = "" put Null in the column.

How can I set a column as zero length string using the SqlDataSource?

Any help is appreciated.

Thanks.

Try:

e.Values("myFld") =string.Empty

|||Check the advanced properties of the parameter in your upate statement. You probably have the property (Sorry, the exact name eludes me) "ChangeEmptyStringToNull" set to true (true is the default).|||Thank you very much. "ConvertEmptyStringToNull" worked perfectly.

Monday, March 26, 2012

How to insert a record in the middle of a DB

Well, how do you do it? I've not seen any report on this... so could it be next to impossible?

Say you have 10 records, 1-10 and you want to insert a new record between record 4 and record 5 in a SQL database, just how do you code it? And oh, each record uses the auto ID increment feature.

Here's an idea:

CREATE TABLE MyTable (id int identity(1,1), col1 varchar(16))
GO

INSERT INTO MyTable SELECT 'value 01'
INSERT INTO MyTable SELECT 'value 02'
INSERT INTO MyTable SELECT 'value 03'
INSERT INTO MyTable SELECT 'value 04'
INSERT INTO MyTable SELECT 'value 05'
INSERT INTO MyTable SELECT 'value 06'
INSERT INTO MyTable SELECT 'value 07'
INSERT INTO MyTable SELECT 'value 08'
INSERT INTO MyTable SELECT 'value 09'
INSERT INTO MyTable SELECT 'value 10'
GO

CREATE TABLE tmpMyTable (id int identity(1,1), col1 varchar(16))
GO

SET IDENTITY_INSERT tmpMyTable ON
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id, col1
FROM MyTable
WHERE id < 5

INSERT INTO tmpMyTable (id,col1) SELECT 5,'value between'
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id+1, col1
FROM MyTable
WHERE id > 4

SET IDENTITY_INSERT tmpMyTable OFF
GO

DROP TABLE MyTable
GO

EXEC sp_rename 'tmpMyTable', 'MyTable'
GO

SELECT * FROM MyTable

|||

Thanks... I'm not very good at SQL but I figure, you create a new table, add those values to it and them insert them back into the old table?

If I can renumber the ID, that would be fine. I deleted record #2 and when I leave record one (view), it still stops where record #2 was deleted. I have to click again to go to record 3. I don't know why it just doesn't jump to record #3, seeing that #2 is deleted.

|||

Take a look at your other question...

Renumbering ID fields is BAD... I really mean it. It can only be done via another table to temporary store the data. There should be no reason to renumber IDs anyway, and if there IS a reson, then the field should not ba an ID ;)

|||

...ooops! That would be "delete" the old table and make the new table the current table.

Okay, ok, this can solve my problem, how can I advance to the next record using code only? I programed my app to go by ID, so if ID #2 is deleted, nothing happens because #2 is deleted. I have to click until the program counter is up to a ID value that isn't deleted before any records show up.

If I say (not really my code, just for example purposes)

CurrRec=CurrRec+1

Select Data from Table1 WHERE ID = CurrRec

Read

While CurrRec is NullDB then

CurrRec=CurrRec+1

Read? 'I could use a read to get pass the deleted record ID

'however, there's a problem if CurrRec > total records

'because it's at the end of the DB

end While

I could put in a time out loop that exits if no record is found in x tries... but surely there must be a way to jump to the NEXT RECORD and a END OF RECORD and so on.

Any takers?

|||

well to move through your records you should do something like this...

Dim oreader As SqlClient.SqlDataReader

Dim oCmd As SqlClient.SqlCommand

oCmd.CommandText = "Select * from mytable"

oreader = oCmd.ExecuteReader

While oreader.Read

'dostuff

End While

|||

I do also need to... move.first, move.last, move.next, ect. With the currRec to move next, I add 1 to currRec, to move back, I subtract 1, to move first, currRec=1.

I'm now thinking I can using CTE functions, if only I can find the syntax for them. That way, I don't use the ID, just the record number.

Thanks.

|||

zdrae,

To select each record, one record at a time, you can use the Top keyword. Each time you get back a record, just save the ID in a variable so that you may use it to select the next record.

EXAMPLE:
Select Top 1 Data from Table1 Where ID > prevID Order by ID

The idea is to select the next record who has an ID greater than the current ID.

Also, just FYI, I think some people in these forums are confused by your use of the term "ID". It seems to me that you really only mean an identity column, but the other posters in this forum are right that you should not attempt to renumber an identity field.

You may be used to programming in a "line-by-line" oriented way, but SQL is really very different and powerful as a data manipulation language. After using it for a while, you'll love how simple and powerful SQL is compared to "line-by-line" data processing.

Hope this helps...

|||

Actually, I didn't like SQL one bit... until I figured out what should actually be in the connection string (I finally got it open); but still I wasn't able to get any data out until I found that I was missing a read statement.

It's on my notebook and the speed is terrible... but everything is slow on it anyway... even games. Thanks.

|||This works great going forward. Any ideas on going backwards? I could store previous IDs but that won't do any good once it goes off the reservation.|||

Instead of a Datareader you could use the Datareader to fill a Dataset or a Datatable.

Those 2 objects will store the data permanently untill you discard them. By doing so they will allow you to scroll foreward and backwards (Or accessing any record you retrieved)

But be aware that you allways should only fetch those records you need...

|||

Yeah, I'm going to put more investment into tableadapters/binding... I just have to figure out how to program it to get the results I need. Wish there was a book... so now I have to make do.

Thanks.

|||

SQL 2005 has a new function called ROW_NUMER. This generates a sequential number, based on another column in the table. So it may eliminate the need for inserting in the middle of the table, and renumbering the IDs. Sample usage:

Select ROW_NUMBER() over (order by MyColumn) as 'SequenceNumber', MyColumn from MyTable

hth

Fluffy

|||

Hi,

As a lot of other replies have said updating an identity column's value is bad. You certainly should not be doing it as part of normal operation of whatever application you are writing to access the database.

Perhaps if you gave a bit of information about what you are actually trying to do with your application in this situation then someone could suggest a better way of doing it. From what you've said so far it simply sounds like you haven't grasped how SQL works and are trying to doing things in an odd way.

Bye,

Dev.

|||In the first place, there's no concept of up or down in space, and there's no concept of 'middle' in a relational database. Indeed, the very essence of a relational database is that the physical location of the rows is irrelevant. So you can't talk about 'inserting a record into the middle of a database' and be talking, sensibly, about a relational database at all. Records go where they go, and that's all there is to it: you leave it up to the RDBMS to work out how to retrieve them, and display them in a user-defined order, when you issue SQL queries against the database.

Second, autoincrementing columns are used to provide meaningless surrogate keys. You suddenly want to start insisting on inserting a new number in between a series of pre-existing auto-incremented ones and what you are actually telling me is that you are reading meaning into what is meant to be, and what was designed to be, meaningless. If you begin changing the auto-assigned numbers to make room for a new entry, and you're actually updating a primary key... and that's just a relational no-no, usually. If the numbers assigned have to have a specific value, they mean something to you, they cannot therefore be meaningless and you shouldn't therefore have used an autoincrementing column to capture them. If, on the other hand, you are happy with autoincrementing numbers, then be happy with them whatever they may be for a particular record, and the question you ask then becomes redundant.

And those who have answered with code samples proposing turning autoincrementing off for a bit, updating the formerly autoincrementing column to make space for the new insert, and the rest... well, frankly, they've missed the point. The request makes no sense as written, demonstrates a fundamental misunderstanding of relational databases and their use, and cannot sensibly be answered.

If there's a specific business problem to be dealt with, that's a different matter ...and one that almost inevitably will come down to fixing a poor application design or being clearer on poorly-understood business requirements.

How to insert a record in the middle of a DB

Well, how do you do it? I've not seen any report on this... so could it be next to impossible?

Say you have 10 records, 1-10 and you want to insert a new record between record 4 and record 5 in a SQL database, just how do you code it? And oh, each record uses the auto ID increment feature.

Here's an idea:

CREATE TABLE MyTable (id int identity(1,1), col1 varchar(16))
GO

INSERT INTO MyTable SELECT 'value 01'
INSERT INTO MyTable SELECT 'value 02'
INSERT INTO MyTable SELECT 'value 03'
INSERT INTO MyTable SELECT 'value 04'
INSERT INTO MyTable SELECT 'value 05'
INSERT INTO MyTable SELECT 'value 06'
INSERT INTO MyTable SELECT 'value 07'
INSERT INTO MyTable SELECT 'value 08'
INSERT INTO MyTable SELECT 'value 09'
INSERT INTO MyTable SELECT 'value 10'
GO

CREATE TABLE tmpMyTable (id int identity(1,1), col1 varchar(16))
GO

SET IDENTITY_INSERT tmpMyTable ON
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id, col1
FROM MyTable
WHERE id < 5

INSERT INTO tmpMyTable (id,col1) SELECT 5,'value between'
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id+1, col1
FROM MyTable
WHERE id > 4

SET IDENTITY_INSERT tmpMyTable OFF
GO

DROP TABLE MyTable
GO

EXEC sp_rename 'tmpMyTable', 'MyTable'
GO

SELECT * FROM MyTable

|||

Thanks... I'm not very good at SQL but I figure, you create a new table, add those values to it and them insert them back into the old table?

If I can renumber the ID, that would be fine. I deleted record #2 and when I leave record one (view), it still stops where record #2 was deleted. I have to click again to go to record 3. I don't know why it just doesn't jump to record #3, seeing that #2 is deleted.

|||

Take a look at your other question...

Renumbering ID fields is BAD... I really mean it. It can only be done via another table to temporary store the data. There should be no reason to renumber IDs anyway, and if there IS a reson, then the field should not ba an ID ;)

|||

...ooops! That would be "delete" the old table and make the new table the current table.

Okay, ok, this can solve my problem, how can I advance to the next record using code only? I programed my app to go by ID, so if ID #2 is deleted, nothing happens because #2 is deleted. I have to click until the program counter is up to a ID value that isn't deleted before any records show up.

If I say (not really my code, just for example purposes)

CurrRec=CurrRec+1

Select Data from Table1 WHERE ID = CurrRec

Read

While CurrRec is NullDB then

CurrRec=CurrRec+1

Read? 'I could use a read to get pass the deleted record ID

'however, there's a problem if CurrRec > total records

'because it's at the end of the DB

end While

I could put in a time out loop that exits if no record is found in x tries... but surely there must be a way to jump to the NEXT RECORD and a END OF RECORD and so on.

Any takers?

|||

well to move through your records you should do something like this...

Dim oreader As SqlClient.SqlDataReader

Dim oCmd As SqlClient.SqlCommand

oCmd.CommandText = "Select * from mytable"

oreader = oCmd.ExecuteReader

While oreader.Read

'dostuff

End While

|||

I do also need to... move.first, move.last, move.next, ect. With the currRec to move next, I add 1 to currRec, to move back, I subtract 1, to move first, currRec=1.

I'm now thinking I can using CTE functions, if only I can find the syntax for them. That way, I don't use the ID, just the record number.

Thanks.

|||

zdrae,

To select each record, one record at a time, you can use the Top keyword. Each time you get back a record, just save the ID in a variable so that you may use it to select the next record.

EXAMPLE:
Select Top 1 Data from Table1 Where ID > prevID Order by ID

The idea is to select the next record who has an ID greater than the current ID.

Also, just FYI, I think some people in these forums are confused by your use of the term "ID". It seems to me that you really only mean an identity column, but the other posters in this forum are right that you should not attempt to renumber an identity field.

You may be used to programming in a "line-by-line" oriented way, but SQL is really very different and powerful as a data manipulation language. After using it for a while, you'll love how simple and powerful SQL is compared to "line-by-line" data processing.

Hope this helps...

|||

Actually, I didn't like SQL one bit... until I figured out what should actually be in the connection string (I finally got it open); but still I wasn't able to get any data out until I found that I was missing a read statement.

It's on my notebook and the speed is terrible... but everything is slow on it anyway... even games. Thanks.

|||This works great going forward. Any ideas on going backwards? I could store previous IDs but that won't do any good once it goes off the reservation.|||

Instead of a Datareader you could use the Datareader to fill a Dataset or a Datatable.

Those 2 objects will store the data permanently untill you discard them. By doing so they will allow you to scroll foreward and backwards (Or accessing any record you retrieved)

But be aware that you allways should only fetch those records you need...

|||

Yeah, I'm going to put more investment into tableadapters/binding... I just have to figure out how to program it to get the results I need. Wish there was a book... so now I have to make do.

Thanks.

|||

SQL 2005 has a new function called ROW_NUMER. This generates a sequential number, based on another column in the table. So it may eliminate the need for inserting in the middle of the table, and renumbering the IDs. Sample usage:

Select ROW_NUMBER() over (order by MyColumn) as 'SequenceNumber', MyColumn from MyTable

hth

Fluffy

|||

Hi,

As a lot of other replies have said updating an identity column's value is bad. You certainly should not be doing it as part of normal operation of whatever application you are writing to access the database.

Perhaps if you gave a bit of information about what you are actually trying to do with your application in this situation then someone could suggest a better way of doing it. From what you've said so far it simply sounds like you haven't grasped how SQL works and are trying to doing things in an odd way.

Bye,

Dev.

|||In the first place, there's no concept of up or down in space, and there's no concept of 'middle' in a relational database. Indeed, the very essence of a relational database is that the physical location of the rows is irrelevant. So you can't talk about 'inserting a record into the middle of a database' and be talking, sensibly, about a relational database at all. Records go where they go, and that's all there is to it: you leave it up to the RDBMS to work out how to retrieve them, and display them in a user-defined order, when you issue SQL queries against the database.

Second, autoincrementing columns are used to provide meaningless surrogate keys. You suddenly want to start insisting on inserting a new number in between a series of pre-existing auto-incremented ones and what you are actually telling me is that you are reading meaning into what is meant to be, and what was designed to be, meaningless. If you begin changing the auto-assigned numbers to make room for a new entry, and you're actually updating a primary key... and that's just a relational no-no, usually. If the numbers assigned have to have a specific value, they mean something to you, they cannot therefore be meaningless and you shouldn't therefore have used an autoincrementing column to capture them. If, on the other hand, you are happy with autoincrementing numbers, then be happy with them whatever they may be for a particular record, and the question you ask then becomes redundant.

And those who have answered with code samples proposing turning autoincrementing off for a bit, updating the formerly autoincrementing column to make space for the new insert, and the rest... well, frankly, they've missed the point. The request makes no sense as written, demonstrates a fundamental misunderstanding of relational databases and their use, and cannot sensibly be answered.

If there's a specific business problem to be dealt with, that's a different matter ...and one that almost inevitably will come down to fixing a poor application design or being clearer on poorly-understood business requirements.

How to insert a record in the middle of a DB

Well, how do you do it? I've not seen any report on this... so could it be next to impossible?

Say you have 10 records, 1-10 and you want to insert a new record between record 4 and record 5 in a SQL database, just how do you code it? And oh, each record uses the auto ID increment feature.

Here's an idea:

CREATE TABLE MyTable (id int identity(1,1), col1 varchar(16))
GO

INSERT INTO MyTable SELECT 'value 01'
INSERT INTO MyTable SELECT 'value 02'
INSERT INTO MyTable SELECT 'value 03'
INSERT INTO MyTable SELECT 'value 04'
INSERT INTO MyTable SELECT 'value 05'
INSERT INTO MyTable SELECT 'value 06'
INSERT INTO MyTable SELECT 'value 07'
INSERT INTO MyTable SELECT 'value 08'
INSERT INTO MyTable SELECT 'value 09'
INSERT INTO MyTable SELECT 'value 10'
GO

CREATE TABLE tmpMyTable (id int identity(1,1), col1 varchar(16))
GO

SET IDENTITY_INSERT tmpMyTable ON
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id, col1
FROM MyTable
WHERE id < 5

INSERT INTO tmpMyTable (id,col1) SELECT 5,'value between'
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id+1, col1
FROM MyTable
WHERE id > 4

SET IDENTITY_INSERT tmpMyTable OFF
GO

DROP TABLE MyTable
GO

EXEC sp_rename 'tmpMyTable', 'MyTable'
GO

SELECT * FROM MyTable

|||

Thanks... I'm not very good at SQL but I figure, you create a new table, add those values to it and them insert them back into the old table?

If I can renumber the ID, that would be fine. I deleted record #2 and when I leave record one (view), it still stops where record #2 was deleted. I have to click again to go to record 3. I don't know why it just doesn't jump to record #3, seeing that #2 is deleted.

|||

Take a look at your other question...

Renumbering ID fields is BAD... I really mean it. It can only be done via another table to temporary store the data. There should be no reason to renumber IDs anyway, and if there IS a reson, then the field should not ba an ID ;)

|||

...ooops! That would be "delete" the old table and make the new table the current table.

Okay, ok, this can solve my problem, how can I advance to the next record using code only? I programed my app to go by ID, so if ID #2 is deleted, nothing happens because #2 is deleted. I have to click until the program counter is up to a ID value that isn't deleted before any records show up.

If I say (not really my code, just for example purposes)

CurrRec=CurrRec+1

Select Data from Table1 WHERE ID = CurrRec

Read

While CurrRec is NullDB then

CurrRec=CurrRec+1

Read? 'I could use a read to get pass the deleted record ID

'however, there's a problem if CurrRec > total records

'because it's at the end of the DB

end While

I could put in a time out loop that exits if no record is found in x tries... but surely there must be a way to jump to the NEXT RECORD and a END OF RECORD and so on.

Any takers?

|||

well to move through your records you should do something like this...

Dim oreader As SqlClient.SqlDataReader

Dim oCmd As SqlClient.SqlCommand

oCmd.CommandText = "Select * from mytable"

oreader = oCmd.ExecuteReader

While oreader.Read

'dostuff

End While

|||

I do also need to... move.first, move.last, move.next, ect. With the currRec to move next, I add 1 to currRec, to move back, I subtract 1, to move first, currRec=1.

I'm now thinking I can using CTE functions, if only I can find the syntax for them. That way, I don't use the ID, just the record number.

Thanks.

|||

zdrae,

To select each record, one record at a time, you can use the Top keyword. Each time you get back a record, just save the ID in a variable so that you may use it to select the next record.

EXAMPLE:
Select Top 1 Data from Table1 Where ID > prevID Order by ID

The idea is to select the next record who has an ID greater than the current ID.

Also, just FYI, I think some people in these forums are confused by your use of the term "ID". It seems to me that you really only mean an identity column, but the other posters in this forum are right that you should not attempt to renumber an identity field.

You may be used to programming in a "line-by-line" oriented way, but SQL is really very different and powerful as a data manipulation language. After using it for a while, you'll love how simple and powerful SQL is compared to "line-by-line" data processing.

Hope this helps...

|||

Actually, I didn't like SQL one bit... until I figured out what should actually be in the connection string (I finally got it open); but still I wasn't able to get any data out until I found that I was missing a read statement.

It's on my notebook and the speed is terrible... but everything is slow on it anyway... even games. Thanks.

|||This works great going forward. Any ideas on going backwards? I could store previous IDs but that won't do any good once it goes off the reservation.|||

Instead of a Datareader you could use the Datareader to fill a Dataset or a Datatable.

Those 2 objects will store the data permanently untill you discard them. By doing so they will allow you to scroll foreward and backwards (Or accessing any record you retrieved)

But be aware that you allways should only fetch those records you need...

|||

Yeah, I'm going to put more investment into tableadapters/binding... I just have to figure out how to program it to get the results I need. Wish there was a book... so now I have to make do.

Thanks.

|||

SQL 2005 has a new function called ROW_NUMER. This generates a sequential number, based on another column in the table. So it may eliminate the need for inserting in the middle of the table, and renumbering the IDs. Sample usage:

Select ROW_NUMBER() over (order by MyColumn) as 'SequenceNumber', MyColumn from MyTable

hth

Fluffy

|||

Hi,

As a lot of other replies have said updating an identity column's value is bad. You certainly should not be doing it as part of normal operation of whatever application you are writing to access the database.

Perhaps if you gave a bit of information about what you are actually trying to do with your application in this situation then someone could suggest a better way of doing it. From what you've said so far it simply sounds like you haven't grasped how SQL works and are trying to doing things in an odd way.

Bye,

Dev.

|||In the first place, there's no concept of up or down in space, and there's no concept of 'middle' in a relational database. Indeed, the very essence of a relational database is that the physical location of the rows is irrelevant. So you can't talk about 'inserting a record into the middle of a database' and be talking, sensibly, about a relational database at all. Records go where they go, and that's all there is to it: you leave it up to the RDBMS to work out how to retrieve them, and display them in a user-defined order, when you issue SQL queries against the database.

Second, autoincrementing columns are used to provide meaningless surrogate keys. You suddenly want to start insisting on inserting a new number in between a series of pre-existing auto-incremented ones and what you are actually telling me is that you are reading meaning into what is meant to be, and what was designed to be, meaningless. If you begin changing the auto-assigned numbers to make room for a new entry, and you're actually updating a primary key... and that's just a relational no-no, usually. If the numbers assigned have to have a specific value, they mean something to you, they cannot therefore be meaningless and you shouldn't therefore have used an autoincrementing column to capture them. If, on the other hand, you are happy with autoincrementing numbers, then be happy with them whatever they may be for a particular record, and the question you ask then becomes redundant.

And those who have answered with code samples proposing turning autoincrementing off for a bit, updating the formerly autoincrementing column to make space for the new insert, and the rest... well, frankly, they've missed the point. The request makes no sense as written, demonstrates a fundamental misunderstanding of relational databases and their use, and cannot sensibly be answered.

If there's a specific business problem to be dealt with, that's a different matter ...and one that almost inevitably will come down to fixing a poor application design or being clearer on poorly-understood business requirements.

How to insert a record in the middle of a DB

Well, how do you do it? I've not seen any report on this... so could it be next to impossible?

Say you have 10 records, 1-10 and you want to insert a new record between record 4 and record 5 in a SQL database, just how do you code it? And oh, each record uses the auto ID increment feature.

Here's an idea:

CREATE TABLE MyTable (id int identity(1,1), col1 varchar(16))
GO

INSERT INTO MyTable SELECT 'value 01'
INSERT INTO MyTable SELECT 'value 02'
INSERT INTO MyTable SELECT 'value 03'
INSERT INTO MyTable SELECT 'value 04'
INSERT INTO MyTable SELECT 'value 05'
INSERT INTO MyTable SELECT 'value 06'
INSERT INTO MyTable SELECT 'value 07'
INSERT INTO MyTable SELECT 'value 08'
INSERT INTO MyTable SELECT 'value 09'
INSERT INTO MyTable SELECT 'value 10'
GO

CREATE TABLE tmpMyTable (id int identity(1,1), col1 varchar(16))
GO

SET IDENTITY_INSERT tmpMyTable ON
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id, col1
FROM MyTable
WHERE id < 5

INSERT INTO tmpMyTable (id,col1) SELECT 5,'value between'
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id+1, col1
FROM MyTable
WHERE id > 4

SET IDENTITY_INSERT tmpMyTable OFF
GO

DROP TABLE MyTable
GO

EXEC sp_rename 'tmpMyTable', 'MyTable'
GO

SELECT * FROM MyTable

|||

Thanks... I'm not very good at SQL but I figure, you create a new table, add those values to it and them insert them back into the old table?

If I can renumber the ID, that would be fine. I deleted record #2 and when I leave record one (view), it still stops where record #2 was deleted. I have to click again to go to record 3. I don't know why it just doesn't jump to record #3, seeing that #2 is deleted.

|||

Take a look at your other question...

Renumbering ID fields is BAD... I really mean it. It can only be done via another table to temporary store the data. There should be no reason to renumber IDs anyway, and if there IS a reson, then the field should not ba an ID ;)

|||

...ooops! That would be "delete" the old table and make the new table the current table.

Okay, ok, this can solve my problem, how can I advance to the next record using code only? I programed my app to go by ID, so if ID #2 is deleted, nothing happens because #2 is deleted. I have to click until the program counter is up to a ID value that isn't deleted before any records show up.

If I say (not really my code, just for example purposes)

CurrRec=CurrRec+1

Select Data from Table1 WHERE ID = CurrRec

Read

While CurrRec is NullDB then

CurrRec=CurrRec+1

Read? 'I could use a read to get pass the deleted record ID

'however, there's a problem if CurrRec > total records

'because it's at the end of the DB

end While

I could put in a time out loop that exits if no record is found in x tries... but surely there must be a way to jump to the NEXT RECORD and a END OF RECORD and so on.

Any takers?

|||

well to move through your records you should do something like this...

Dim oreader As SqlClient.SqlDataReader

Dim oCmd As SqlClient.SqlCommand

oCmd.CommandText = "Select * from mytable"

oreader = oCmd.ExecuteReader

While oreader.Read

'dostuff

End While

|||

I do also need to... move.first, move.last, move.next, ect. With the currRec to move next, I add 1 to currRec, to move back, I subtract 1, to move first, currRec=1.

I'm now thinking I can using CTE functions, if only I can find the syntax for them. That way, I don't use the ID, just the record number.

Thanks.

|||

zdrae,

To select each record, one record at a time, you can use the Top keyword. Each time you get back a record, just save the ID in a variable so that you may use it to select the next record.

EXAMPLE:
Select Top 1 Data from Table1 Where ID > prevID Order by ID

The idea is to select the next record who has an ID greater than the current ID.

Also, just FYI, I think some people in these forums are confused by your use of the term "ID". It seems to me that you really only mean an identity column, but the other posters in this forum are right that you should not attempt to renumber an identity field.

You may be used to programming in a "line-by-line" oriented way, but SQL is really very different and powerful as a data manipulation language. After using it for a while, you'll love how simple and powerful SQL is compared to "line-by-line" data processing.

Hope this helps...

|||

Actually, I didn't like SQL one bit... until I figured out what should actually be in the connection string (I finally got it open); but still I wasn't able to get any data out until I found that I was missing a read statement.

It's on my notebook and the speed is terrible... but everything is slow on it anyway... even games. Thanks.

|||This works great going forward. Any ideas on going backwards? I could store previous IDs but that won't do any good once it goes off the reservation.|||

Instead of a Datareader you could use the Datareader to fill a Dataset or a Datatable.

Those 2 objects will store the data permanently untill you discard them. By doing so they will allow you to scroll foreward and backwards (Or accessing any record you retrieved)

But be aware that you allways should only fetch those records you need...

|||

Yeah, I'm going to put more investment into tableadapters/binding... I just have to figure out how to program it to get the results I need. Wish there was a book... so now I have to make do.

Thanks.

|||

SQL 2005 has a new function called ROW_NUMER. This generates a sequential number, based on another column in the table. So it may eliminate the need for inserting in the middle of the table, and renumbering the IDs. Sample usage:

Select ROW_NUMBER() over (order by MyColumn) as 'SequenceNumber', MyColumn from MyTable

hth

Fluffy

|||

Hi,

As a lot of other replies have said updating an identity column's value is bad. You certainly should not be doing it as part of normal operation of whatever application you are writing to access the database.

Perhaps if you gave a bit of information about what you are actually trying to do with your application in this situation then someone could suggest a better way of doing it. From what you've said so far it simply sounds like you haven't grasped how SQL works and are trying to doing things in an odd way.

Bye,

Dev.

|||In the first place, there's no concept of up or down in space, and there's no concept of 'middle' in a relational database. Indeed, the very essence of a relational database is that the physical location of the rows is irrelevant. So you can't talk about 'inserting a record into the middle of a database' and be talking, sensibly, about a relational database at all. Records go where they go, and that's all there is to it: you leave it up to the RDBMS to work out how to retrieve them, and display them in a user-defined order, when you issue SQL queries against the database.

Second, autoincrementing columns are used to provide meaningless surrogate keys. You suddenly want to start insisting on inserting a new number in between a series of pre-existing auto-incremented ones and what you are actually telling me is that you are reading meaning into what is meant to be, and what was designed to be, meaningless. If you begin changing the auto-assigned numbers to make room for a new entry, and you're actually updating a primary key... and that's just a relational no-no, usually. If the numbers assigned have to have a specific value, they mean something to you, they cannot therefore be meaningless and you shouldn't therefore have used an autoincrementing column to capture them. If, on the other hand, you are happy with autoincrementing numbers, then be happy with them whatever they may be for a particular record, and the question you ask then becomes redundant.

And those who have answered with code samples proposing turning autoincrementing off for a bit, updating the formerly autoincrementing column to make space for the new insert, and the rest... well, frankly, they've missed the point. The request makes no sense as written, demonstrates a fundamental misunderstanding of relational databases and their use, and cannot sensibly be answered.

If there's a specific business problem to be dealt with, that's a different matter ...and one that almost inevitably will come down to fixing a poor application design or being clearer on poorly-understood business requirements.

How to insert a record in the middle of a DB

Well, how do you do it? I've not seen any report on this... so could it be next to impossible?

Say you have 10 records, 1-10 and you want to insert a new record between record 4 and record 5 in a SQL database, just how do you code it? And oh, each record uses the auto ID increment feature.

Here's an idea:

CREATE TABLE MyTable (id int identity(1,1), col1 varchar(16))
GO

INSERT INTO MyTable SELECT 'value 01'
INSERT INTO MyTable SELECT 'value 02'
INSERT INTO MyTable SELECT 'value 03'
INSERT INTO MyTable SELECT 'value 04'
INSERT INTO MyTable SELECT 'value 05'
INSERT INTO MyTable SELECT 'value 06'
INSERT INTO MyTable SELECT 'value 07'
INSERT INTO MyTable SELECT 'value 08'
INSERT INTO MyTable SELECT 'value 09'
INSERT INTO MyTable SELECT 'value 10'
GO

CREATE TABLE tmpMyTable (id int identity(1,1), col1 varchar(16))
GO

SET IDENTITY_INSERT tmpMyTable ON
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id, col1
FROM MyTable
WHERE id < 5

INSERT INTO tmpMyTable (id,col1) SELECT 5,'value between'
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id+1, col1
FROM MyTable
WHERE id > 4

SET IDENTITY_INSERT tmpMyTable OFF
GO

DROP TABLE MyTable
GO

EXEC sp_rename 'tmpMyTable', 'MyTable'
GO

SELECT * FROM MyTable

|||

Thanks... I'm not very good at SQL but I figure, you create a new table, add those values to it and them insert them back into the old table?

If I can renumber the ID, that would be fine. I deleted record #2 and when I leave record one (view), it still stops where record #2 was deleted. I have to click again to go to record 3. I don't know why it just doesn't jump to record #3, seeing that #2 is deleted.

|||

Take a look at your other question...

Renumbering ID fields is BAD... I really mean it. It can only be done via another table to temporary store the data. There should be no reason to renumber IDs anyway, and if there IS a reson, then the field should not ba an ID ;)

|||

...ooops! That would be "delete" the old table and make the new table the current table.

Okay, ok, this can solve my problem, how can I advance to the next record using code only? I programed my app to go by ID, so if ID #2 is deleted, nothing happens because #2 is deleted. I have to click until the program counter is up to a ID value that isn't deleted before any records show up.

If I say (not really my code, just for example purposes)

CurrRec=CurrRec+1

Select Data from Table1 WHERE ID = CurrRec

Read

While CurrRec is NullDB then

CurrRec=CurrRec+1

Read? 'I could use a read to get pass the deleted record ID

'however, there's a problem if CurrRec > total records

'because it's at the end of the DB

end While

I could put in a time out loop that exits if no record is found in x tries... but surely there must be a way to jump to the NEXT RECORD and a END OF RECORD and so on.

Any takers?

|||

well to move through your records you should do something like this...

Dim oreader As SqlClient.SqlDataReader

Dim oCmd As SqlClient.SqlCommand

oCmd.CommandText = "Select * from mytable"

oreader = oCmd.ExecuteReader

While oreader.Read

'dostuff

End While

|||

I do also need to... move.first, move.last, move.next, ect. With the currRec to move next, I add 1 to currRec, to move back, I subtract 1, to move first, currRec=1.

I'm now thinking I can using CTE functions, if only I can find the syntax for them. That way, I don't use the ID, just the record number.

Thanks.

|||

zdrae,

To select each record, one record at a time, you can use the Top keyword. Each time you get back a record, just save the ID in a variable so that you may use it to select the next record.

EXAMPLE:
Select Top 1 Data from Table1 Where ID > prevID Order by ID

The idea is to select the next record who has an ID greater than the current ID.

Also, just FYI, I think some people in these forums are confused by your use of the term "ID". It seems to me that you really only mean an identity column, but the other posters in this forum are right that you should not attempt to renumber an identity field.

You may be used to programming in a "line-by-line" oriented way, but SQL is really very different and powerful as a data manipulation language. After using it for a while, you'll love how simple and powerful SQL is compared to "line-by-line" data processing.

Hope this helps...

|||

Actually, I didn't like SQL one bit... until I figured out what should actually be in the connection string (I finally got it open); but still I wasn't able to get any data out until I found that I was missing a read statement.

It's on my notebook and the speed is terrible... but everything is slow on it anyway... even games. Thanks.

|||This works great going forward. Any ideas on going backwards? I could store previous IDs but that won't do any good once it goes off the reservation.|||

Instead of a Datareader you could use the Datareader to fill a Dataset or a Datatable.

Those 2 objects will store the data permanently untill you discard them. By doing so they will allow you to scroll foreward and backwards (Or accessing any record you retrieved)

But be aware that you allways should only fetch those records you need...

|||

Yeah, I'm going to put more investment into tableadapters/binding... I just have to figure out how to program it to get the results I need. Wish there was a book... so now I have to make do.

Thanks.

|||

SQL 2005 has a new function called ROW_NUMER. This generates a sequential number, based on another column in the table. So it may eliminate the need for inserting in the middle of the table, and renumbering the IDs. Sample usage:

Select ROW_NUMBER() over (order by MyColumn) as 'SequenceNumber', MyColumn from MyTable

hth

Fluffy

|||

Hi,

As a lot of other replies have said updating an identity column's value is bad. You certainly should not be doing it as part of normal operation of whatever application you are writing to access the database.

Perhaps if you gave a bit of information about what you are actually trying to do with your application in this situation then someone could suggest a better way of doing it. From what you've said so far it simply sounds like you haven't grasped how SQL works and are trying to doing things in an odd way.

Bye,

Dev.

|||In the first place, there's no concept of up or down in space, and there's no concept of 'middle' in a relational database. Indeed, the very essence of a relational database is that the physical location of the rows is irrelevant. So you can't talk about 'inserting a record into the middle of a database' and be talking, sensibly, about a relational database at all. Records go where they go, and that's all there is to it: you leave it up to the RDBMS to work out how to retrieve them, and display them in a user-defined order, when you issue SQL queries against the database.

Second, autoincrementing columns are used to provide meaningless surrogate keys. You suddenly want to start insisting on inserting a new number in between a series of pre-existing auto-incremented ones and what you are actually telling me is that you are reading meaning into what is meant to be, and what was designed to be, meaningless. If you begin changing the auto-assigned numbers to make room for a new entry, and you're actually updating a primary key... and that's just a relational no-no, usually. If the numbers assigned have to have a specific value, they mean something to you, they cannot therefore be meaningless and you shouldn't therefore have used an autoincrementing column to capture them. If, on the other hand, you are happy with autoincrementing numbers, then be happy with them whatever they may be for a particular record, and the question you ask then becomes redundant.

And those who have answered with code samples proposing turning autoincrementing off for a bit, updating the formerly autoincrementing column to make space for the new insert, and the rest... well, frankly, they've missed the point. The request makes no sense as written, demonstrates a fundamental misunderstanding of relational databases and their use, and cannot sensibly be answered.

If there's a specific business problem to be dealt with, that's a different matter ...and one that almost inevitably will come down to fixing a poor application design or being clearer on poorly-understood business requirements.

How to insert a record in the middle of a DB

Well, how do you do it? I've not seen any report on this... so could it be next to impossible?

Say you have 10 records, 1-10 and you want to insert a new record between record 4 and record 5 in a SQL database, just how do you code it? And oh, each record uses the auto ID increment feature.

Here's an idea:

CREATE TABLE MyTable (id int identity(1,1), col1 varchar(16))
GO

INSERT INTO MyTable SELECT 'value 01'
INSERT INTO MyTable SELECT 'value 02'
INSERT INTO MyTable SELECT 'value 03'
INSERT INTO MyTable SELECT 'value 04'
INSERT INTO MyTable SELECT 'value 05'
INSERT INTO MyTable SELECT 'value 06'
INSERT INTO MyTable SELECT 'value 07'
INSERT INTO MyTable SELECT 'value 08'
INSERT INTO MyTable SELECT 'value 09'
INSERT INTO MyTable SELECT 'value 10'
GO

CREATE TABLE tmpMyTable (id int identity(1,1), col1 varchar(16))
GO

SET IDENTITY_INSERT tmpMyTable ON
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id, col1
FROM MyTable
WHERE id < 5

INSERT INTO tmpMyTable (id,col1) SELECT 5,'value between'
GO

INSERT INTO tmpMyTable (id,col1)
SELECT id+1, col1
FROM MyTable
WHERE id > 4

SET IDENTITY_INSERT tmpMyTable OFF
GO

DROP TABLE MyTable
GO

EXEC sp_rename 'tmpMyTable', 'MyTable'
GO

SELECT * FROM MyTable

|||

Thanks... I'm not very good at SQL but I figure, you create a new table, add those values to it and them insert them back into the old table?

If I can renumber the ID, that would be fine. I deleted record #2 and when I leave record one (view), it still stops where record #2 was deleted. I have to click again to go to record 3. I don't know why it just doesn't jump to record #3, seeing that #2 is deleted.

|||

Take a look at your other question...

Renumbering ID fields is BAD... I really mean it. It can only be done via another table to temporary store the data. There should be no reason to renumber IDs anyway, and if there IS a reson, then the field should not ba an ID ;)

|||

...ooops! That would be "delete" the old table and make the new table the current table.

Okay, ok, this can solve my problem, how can I advance to the next record using code only? I programed my app to go by ID, so if ID #2 is deleted, nothing happens because #2 is deleted. I have to click until the program counter is up to a ID value that isn't deleted before any records show up.

If I say (not really my code, just for example purposes)

CurrRec=CurrRec+1

Select Data from Table1 WHERE ID = CurrRec

Read

While CurrRec is NullDB then

CurrRec=CurrRec+1

Read? 'I could use a read to get pass the deleted record ID

'however, there's a problem if CurrRec > total records

'because it's at the end of the DB

end While

I could put in a time out loop that exits if no record is found in x tries... but surely there must be a way to jump to the NEXT RECORD and a END OF RECORD and so on.

Any takers?

|||

well to move through your records you should do something like this...

Dim oreader As SqlClient.SqlDataReader

Dim oCmd As SqlClient.SqlCommand

oCmd.CommandText = "Select * from mytable"

oreader = oCmd.ExecuteReader

While oreader.Read

'dostuff

End While

|||

I do also need to... move.first, move.last, move.next, ect. With the currRec to move next, I add 1 to currRec, to move back, I subtract 1, to move first, currRec=1.

I'm now thinking I can using CTE functions, if only I can find the syntax for them. That way, I don't use the ID, just the record number.

Thanks.

|||

zdrae,

To select each record, one record at a time, you can use the Top keyword. Each time you get back a record, just save the ID in a variable so that you may use it to select the next record.

EXAMPLE:
Select Top 1 Data from Table1 Where ID > prevID Order by ID

The idea is to select the next record who has an ID greater than the current ID.

Also, just FYI, I think some people in these forums are confused by your use of the term "ID". It seems to me that you really only mean an identity column, but the other posters in this forum are right that you should not attempt to renumber an identity field.

You may be used to programming in a "line-by-line" oriented way, but SQL is really very different and powerful as a data manipulation language. After using it for a while, you'll love how simple and powerful SQL is compared to "line-by-line" data processing.

Hope this helps...

|||

Actually, I didn't like SQL one bit... until I figured out what should actually be in the connection string (I finally got it open); but still I wasn't able to get any data out until I found that I was missing a read statement.

It's on my notebook and the speed is terrible... but everything is slow on it anyway... even games. Thanks.

|||This works great going forward. Any ideas on going backwards? I could store previous IDs but that won't do any good once it goes off the reservation.|||

Instead of a Datareader you could use the Datareader to fill a Dataset or a Datatable.

Those 2 objects will store the data permanently untill you discard them. By doing so they will allow you to scroll foreward and backwards (Or accessing any record you retrieved)

But be aware that you allways should only fetch those records you need...

|||

Yeah, I'm going to put more investment into tableadapters/binding... I just have to figure out how to program it to get the results I need. Wish there was a book... so now I have to make do.

Thanks.

|||

SQL 2005 has a new function called ROW_NUMER. This generates a sequential number, based on another column in the table. So it may eliminate the need for inserting in the middle of the table, and renumbering the IDs. Sample usage:

Select ROW_NUMBER() over (order by MyColumn) as 'SequenceNumber', MyColumn from MyTable

hth

Fluffy

|||

Hi,

As a lot of other replies have said updating an identity column's value is bad. You certainly should not be doing it as part of normal operation of whatever application you are writing to access the database.

Perhaps if you gave a bit of information about what you are actually trying to do with your application in this situation then someone could suggest a better way of doing it. From what you've said so far it simply sounds like you haven't grasped how SQL works and are trying to doing things in an odd way.

Bye,

Dev.

|||In the first place, there's no concept of up or down in space, and there's no concept of 'middle' in a relational database. Indeed, the very essence of a relational database is that the physical location of the rows is irrelevant. So you can't talk about 'inserting a record into the middle of a database' and be talking, sensibly, about a relational database at all. Records go where they go, and that's all there is to it: you leave it up to the RDBMS to work out how to retrieve them, and display them in a user-defined order, when you issue SQL queries against the database.

Second, autoincrementing columns are used to provide meaningless surrogate keys. You suddenly want to start insisting on inserting a new number in between a series of pre-existing auto-incremented ones and what you are actually telling me is that you are reading meaning into what is meant to be, and what was designed to be, meaningless. If you begin changing the auto-assigned numbers to make room for a new entry, and you're actually updating a primary key... and that's just a relational no-no, usually. If the numbers assigned have to have a specific value, they mean something to you, they cannot therefore be meaningless and you shouldn't therefore have used an autoincrementing column to capture them. If, on the other hand, you are happy with autoincrementing numbers, then be happy with them whatever they may be for a particular record, and the question you ask then becomes redundant.

And those who have answered with code samples proposing turning autoincrementing off for a bit, updating the formerly autoincrementing column to make space for the new insert, and the rest... well, frankly, they've missed the point. The request makes no sense as written, demonstrates a fundamental misunderstanding of relational databases and their use, and cannot sensibly be answered.

If there's a specific business problem to be dealt with, that's a different matter ...and one that almost inevitably will come down to fixing a poor application design or being clearer on poorly-understood business requirements.

how to insert a NULL in a table

hello,
in a table i have a field of type bit which allows NULL.
if a new record is created and the field is not set a NULL value is created.
Now my question: if the field was set to the value 0 or 1 how can i reset
that field manualy to NULL. Can i use some key STRG + ...?
thanksUsing the Enterprise manager you can use STRG + 0 to insert a NULL,
using an update statement it would be:
UPDATE Sometable SET SomeColumn = NULL Where is = SomeIdValue
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--|||thanks for your help
"Jens" wrote:

> Using the Enterprise manager you can use STRG + 0 to insert a NULL,
> using an update statement it would be:
> UPDATE Sometable SET SomeColumn = NULL Where is = SomeIdValue
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>|||Through the GUI its usually CTRL 0 together.
With command line its
UPDATE <table>
SET yourcol = NULL
WHERE ...
Tony.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Xavier" <Xavier@.discussions.microsoft.com> wrote in message
news:B7AB5BA4-8AAB-425C-9668-1C435E96A613@.microsoft.com...
> hello,
> in a table i have a field of type bit which allows NULL.
> if a new record is created and the field is not set a NULL value is
> created.
> Now my question: if the field was set to the value 0 or 1 how can i reset
> that field manualy to NULL. Can i use some key STRG + ...?
> thanks
>|||thanks Toni
"Tony Rogerson" wrote:

> Through the GUI its usually CTRL 0 together.
> With command line its
> UPDATE <table>
> SET yourcol = NULL
> WHERE ...
> Tony.
> --
> Tony Rogerson
> SQL Server MVP
> http://sqlserverfaq.com - free video tutorials
>
> "Xavier" <Xavier@.discussions.microsoft.com> wrote in message
> news:B7AB5BA4-8AAB-425C-9668-1C435E96A613@.microsoft.com...
>
>

How to insert a new record (and get it's identity), if a record is not found

What I'm trying to do is write a query (actually it will be a sub-query) that gets the ID of a record using a standard SELECT/WHERE, but if the record is not found then I want to insert a record and return the ID of the inserted record.

So far I've got this (which doesn't work!)

SELECT ISNULL((Select ContactID AS ID FROM [TileManager].[dbo].[Contact] WHERE ([Salutation] = 'Mrs' AND [Forename] = 'Freda' AND [Surname] = 'Bloggs')), (INSERT INTO [TileManager].[dbo].[Contact] ([Salutation],[Forename],[Surname]) VALUES ('Mrs','Freda','Bloggs'); SELECT @.@.IDENTITY AS ID))

Any help would be greatly appreciated.

Rob:

Be careful using the @.@.identity function; try SCOPE_IDENTITY() instead. Look it up in the books.

Dave

|||

I don't believe you can embedded the insert statement like that - why aren't you trying something like this

INSERT Contact (Salutation,Forename,Surname) SELECT 'Mrs','Freda','Bloggs'
WHERE NOT EXISTS (SELECT ID FROM Contact WHERE Salutation = 'Mrs' AND Forename = 'Freda' AND Surname = 'Bloggs')
SELECT ID = @.@.IDENTITY

|||

SELECT ID = @.@.identity will almost always work; it can experience problems such as:

-- -
-- Illustrate the difference between @.@.identity and scopy_identity()
--
-- In this example, @.@.identity returns the value of the identity
-- that was inserted by the trigger
-- -
set nocount on

create table dbo.whatA ( what1 integer identity)
go
create table dbo.whatB ( what2 integer identity)
go

insert into whatA default values insert into WhatA default values
insert into whatB default values
insert into whatA default values insert into WhatA default values
insert into whatA default values insert into WhatA default values

--select * from whatA
--select * from whatB
go

create trigger dbo.trI_whatB on whatB
for insert
as
begin
insert into whatA default values
end

go

insert into whatB default values
select @.@.identity as [Incorrect @.@.Identity]
select scope_identity() as [Correct scope_identity()]
select max (what1) as [WhatA Identity] from whatA
select max (what2) as [WhatB Identity] from whatB
go

drop trigger dbo.trI_whatB
go
drop table dbo.whatA
go
drop table dbo.whatB
go


--
-- O U T P U T :
--


-- Incorrect @.@.Identity
-- -
-- 7

-- Correct scope_identity()
-- -
-- 2

-- WhatA Identity
-- --
-- 7

-- WhatB Identity
-- --
-- 2

|||

That's close to what I'm trying to get, but, what I want is the ID of the record if it is found or the ID of the added record if it is not found. The code you've given returns NULL if the record already exists.

Thanks

|||

INSERT Contact (Salutation,Forename,Surname) SELECT 'Mrs','Freda','Bloggs'
WHERE NOT EXISTS (SELECT ID FROM Contact WHERE Salutation = 'Mrs' AND Forename = 'Freda' AND Surname = 'Bloggs')

SELECT ID FROM Contact WHERE Salutation = 'Mrs' AND Forename = 'Freda' AND Surname = 'Bloggs'

is it acceptable for you to do it as two statements like this?

AWAL

|||

This will do the existance check first and only insert if no record is found...

DECLARE @.ID int

--Get value if existing

SELECT @.ID

FROM [TileManager].[dbo].[Contact]

WHERE ([Salutation] = 'Mrs' AND [Forename] = 'Freda' AND [Surname] = 'Bloggs');

--No value found so insert

IF @.ID IS NULL

BEGIN

INSERT INTO [TileManager].[dbo].[Contact] ([Salutation],[Forename],[Surname]) VALUES ('Mrs','Freda','Bloggs');

SELECT @.ID = SCOPE_IDENTITY();

END

--Use ID for something

SELECT @.ID

sql

How to insert a lookup table row aftre lookup fails

I want to do a a look-up, then if that lookup does not find a record I want to insert a new record into the lookup table, so that effectively the lookup now succeeds.

How can I do that? I can't figure that one out.

TIAI have solved this problem.

I am using a two pass mechanism in the Control Flow. In the first pass (first Data Flow) I do a lookup and then on failure redirct to insert the records.

I have a number of these to do - so in the first pass I multicast the source data to each of the lookups.
You see, I am loading survey data entered into Excel spreadsheets by humans. :)|||FYI it is often more performant not to redirect the error rows but to just do a filter on the rows that don't have the lookup value. This is all down to the redirect creating a new row, and the associated costs of assigning memory etc.
where as processing the normal flow no extra data has to be created in the buffer.

Does that make sense?|||It certainly does Simon. Thank-you very much ... i did not think of that. :)|||

SimonSa wrote:

FYI it is often more performant not to redirect the error rows but to just do a filter on the rows that don't have the lookup value. ...
Does that make sense?

Simon,

Maybe you can provide some insight on a similar scenario. In my control flow, I do a bunch of processing over millions of rows and finally I want to insert a subset into an xyz_master table. However, I want to check if the record already exists or not. I am using the error row redirecting mechanism and it is painfully slow. As per your suggestion, I should do some kind of filter. How do I do it?

Let me know if I need to explain further.

TIA,
Nitesh|||So you have you output from the lookup which is the input to the lookup along with a value that was looked up, i.e the lookup value. For rows found in the lookup this column will contain the key and rows not found will be empty.

This extra column is added to the buffer so the whole row doesn't have to be copied to a new buffer, which is what happens with the redirect, only the new column value is populated in the existing buffer

You then use the conditional split to only output those rows with no value in the lookup key column. The key here is that the conditional split is a synchronous transform and so again uses the same buffer so no data is copied.

You can then use the output of the conditional split (the one where lookup column is null) in any other component.

One thing I will say is that if you are using the lookup make sure you are only selecting the columns you need from the lookup tables, i.e. just the lookup value and any other values needed to be added to the flow.|||Great ... that is exactly what I did :) Glad to see I am on the right track.

I love SSIS!

How to insert 4 records for every one found?

This SQL will insert one record into #Pivot1 for every one
record returned by the SELECT statement:
---
INSERT INTO #Pivot1
(
PersonID,
ProjectID,
Estimate5,
Available5
)
SELECT
wr.PersonID,
ln.ProjectID,
hr.Hours,
wr.HoursAvailable
FROM (tblWeekReported wr
INNER JOIN tblWeekReportedLine ln ON wr.WeekReportedID = ln.WeekReportedID)
INNER JOIN tblHour hr ON ln.WeekReportedLineID = hr.WeekReportedLineID
WHERE
(
(wr.BeginDate=@.BeginDate5) AND
(wr.EndDate=@.EndDate5) AND
(wr.WeekType=2) -- 2=Monthly
);
---
What I need to do, however, is to split each of the incoming records up
into 4 inserts to #Pivot1, dividing 'Hours' and 'HoursAvailable' by 4
for each record.
I guess the brute force method would be to just run that snippet of SQL
four times... but is there a "right" way?
--
PeteCresswellOops! I think I may have something:
---
INSERT INTO #Pivot1
(
PersonID,
ProjectID,
Estimate5,
Available5
)
SELECT
wr.PersonID,
ln.ProjectID,
hr.Hours/4,
wr.HoursAvailable/4
FROM (tblWeekReported wr
INNER JOIN tblWeekReportedLine ln ON wr.WeekReportedID = ln.WeekReportedID)
INNER JOIN tblHour hr ON ln.WeekReportedLineID =hr.WeekReportedLineID
WHERE
(
(wr.BeginDate=@.BeginDate5) AND
(wr.EndDate=@.EndDate5) AND
(wr.WeekType=2) -- 2=Monthly
);
INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
---
Am I on the right track?
--
PeteCresswell|||RE/
>INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
>INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
>INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
"Oops" again: strike that last INSERT - it would
have given us 8 copies of each rec instead of 4...
--
PeteCresswell|||That wouldn't work, you'd end up with far too many records.
--
HTH
Ryan Waight, MCDBA, MCSE
"(Pete Cresswell)" <x@.y.z> wrote in message
news:0k3vqv0fr0s2763bmgfma27re6e4lbglhc@.4ax.com...
> Oops! I think I may have something:
> ---
> INSERT INTO #Pivot1
> (
> PersonID,
> ProjectID,
> Estimate5,
> Available5
> )
> SELECT
> wr.PersonID,
> ln.ProjectID,
> hr.Hours/4,
> wr.HoursAvailable/4
> FROM (tblWeekReported wr
> INNER JOIN tblWeekReportedLine ln ON wr.WeekReportedID =ln.WeekReportedID)
> INNER JOIN tblHour hr ON ln.WeekReportedLineID => hr.WeekReportedLineID
> WHERE
> (
> (wr.BeginDate=@.BeginDate5) AND
> (wr.EndDate=@.EndDate5) AND
> (wr.WeekType=2) -- 2=Monthly
> );
> INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
> INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
> INSERT INTO #Pivot1 SELECT * FROM #Pivot1;
> ---
> Am I on the right track?
> --
> PeteCresswell|||On Mon, 10 Nov 2003 13:05:03 GMT, "(Pete Cresswell)" <x@.y.z> wrote:
>This SQL will insert one record into #Pivot1 for every one
>record returned by the SELECT statement:
>...<snip>...
>What I need to do, however, is to split each of the incoming records up
>into 4 inserts to #Pivot1, dividing 'Hours' and 'HoursAvailable' by 4
>for each record.
>I guess the brute force method would be to just run that snippet of SQL
>four times... but is there a "right" way?
I don't know about right way, but here's a couple of ways:
a) after inserting these rows, select them and insert again (thus
doubling them). Then select them and insert them once more (thus
doubling the double, i.e. four rows for each original one)
b) create a temp table, populate with four records, and join to it in
the select part of your statement. A cartesian join (i.e. no criteria
for the join so that all rows from your temp table are selected and
joined with all rows from the rest of your query) will mean that each
row will appear four times in your result set. This would be my
preference, as it involves a single insert (except for the temp table :)
Of course, if you did this regularly enough, you might want to leave the
table of four rows around permanently, ready to join with. Kind of like
the DUAL table in Oracle these days, that provides a hack method for
returning results from functions without referencing a "real" table.
cheers,
Ross.
--
Ross McKay, WebAware Pty Ltd
"Words can only hurt if you try to read them. Don't play their game" - Zoolander

How to input?

Hi again was just wondering what the best way is too write a script too write a script to record a sale of a workofart? into Sales and WorkOfArt Tables?
Thx :confused:I'm not sure I understand what you want, so we'll start with:INSERT INTO Sales (column_list1) VALUES (column_values1)

INSERT INTO Workofart (column_list2) VALUES (column_values2)I must be missing something, this seems way too easy.

-PatP

how to initialize package variables?

I have a For Loop container where each iteration a Master record is inserted. I also have a number of package variables capturing rowcounts from the dataflow task. I later update the master record with the rowcounts. How do I initialize the package variables containing the rowcounts because currently, some of the rowcounts are being populated with rowcounts from another file.

thanks

jpsR1 wrote:

I have a For Loop container where each iteration a Master record is inserted. I also have a number of package variables capturing rowcounts from the dataflow task. I later update the master record with the rowcounts. How do I initialize the package variables containing the rowcounts because currently, some of the rowcounts are being populated with rowcounts from another file.

thanks

The best way would be to do it in a script task. There's lots of material around to help you do this. Search for "ReadWriteVariables".

-Jamie

|||

Thanks Jamie. I did find some info but it helped when i searched for "ReadWriteVariables".

this is what I used. I had found a similar sample elsewhere and had tried it with no luck. The difference being, I originally had not put the prefix "User::" in front of the variable.

Phil / Mike, thanks for the help...

Now I'm actually confused (seems to happen alot since I delved into SQL 2005!). I actually placed the "User::" tag in front of my variables and it worked. Oh well, I have enough to play with for now (I especially like the functions for the read / write capabilities). I'm really just trying to start refreshing my scripting skills (or obviously lack thereof)...

You actually can put the "User::" in on the Script Task Editor and it works...

If I define the variables "User::varFTPDestPath" and "User::varFTPFileName" as ReadOnly and "User::varFTPDestPathFileName" as ReadWrite in the Script Task Editor, the following works:

Public Sub Main()

Dim strFTPDestPath, strFTPFileName As String
strFTPDestPath = Dts.Variables("User::varFTPSourcePath").Value.ToString
strFTPFileName = Dts.Variables("User::varFTPFileName").Value.ToString
Dts.Variables("User::varSourcePathFileName").Value = strFTPDestPath + strFTPFileName
MsgBox("varSourcePathFileName = " + Dts.Variables("User::varSourcePathFileName").Value.ToString)
Dts.TaskResult = Dts.Results.Success

End Sub

verbatim:

Dts.Variables("User::rcSourceFile").Value = 0

Dts.Variables("User::rcCleanInserts").Value = 0

thanks again!!!

sql