Showing posts with label insert. Show all posts
Showing posts with label insert. Show all posts

Wednesday, March 28, 2012

Multi Row Insert

According to the CTP3 BOL the following code should work just fine, unfortunately is giving me the error message (below the code):

create table FamilyNames (

Id int identity,

[Name] varchar(30)

);

go

insert into FamilyNames values (

('Andersson'),

('Ben-Gan'),

('Carlsson'),

('Davidsen')

);

Msg 213, Level 16, State 1, Line 1
Column name or number of supplied values does not match table definition.

Does anybody know why this code fails?

Hi,


Try

insert into FamilyNames values

('Andersson'),

('Ben-Gan'),

('Carlsson'),

('Davidsen');

Kind regards,

Wesley

|||Thanks.

Multi Record Insert

Hi,
This works:
INSERT INTO test (valueField) VALUES (1);
This does NOT:
INSERT INTO test (valueField) VALUES (1),(2),(3);
Why and how do i make it work? i want to insert multiple records with one
insert statement.. if i insert each one seperately then it takes too long..
i guess i could use transaction locking... but isn't there an easy (aNSI
compatible) way of inserting many records quickly with as few statements as
possible?
I am trying to compare MySQL 4.1 and 5 to SQL Server 2005 and i would most
like to have SQL statements that work in both.
Thanks for any help!
Ok i am have to create a program that per SQL over ODBC is compatible with
different DBMS's. Qurrently i have a proUse INSERT...SELECT:
insert <table>
(
<column>
)
select <column>
union all
select <column>
union all
select <column>
..
ML
http://milambda.blogspot.com/

Friday, March 23, 2012

Multi access in SQL Server

Hello,

I am working on an Access VBA application, working in client/server
mode, with a shared SQL Server base.

I have to INSERT some data in the base, and the know what is the ID
that SQL Server associated with my data in the table. So I need to do
the following

INSERT data INTO TABLE
SELECT MAX ID FROM TABLE (to get the ID)

but since I am working in client/server, if some DATA has been inserted
by another client after my INSERT, then MAX ID is not the convenient
ID of my data ...

Is there a way for me to get the ID when I do the INSERT, or to
lock/unlock the table before the INSERT and after the SELECT ?

Thank you for any hint about that.

--
L'ordinateur peut faire plus de calculs que le cerveau de l'homme car
il n'a que a faireByB (email@.email.com) writes:

Quote:

Originally Posted by

I am working on an Access VBA application, working in client/server
mode, with a shared SQL Server base.
>
I have to INSERT some data in the base, and the know what is the ID
that SQL Server associated with my data in the table. So I need to do
the following
>
INSERT data INTO TABLE
SELECT MAX ID FROM TABLE (to get the ID)
>
but since I am working in client/server, if some DATA has been inserted
by another client after my INSERT, then MAX ID is not the convenient
ID of my data ...
>
Is there a way for me to get the ID when I do the INSERT, or to
lock/unlock the table before the INSERT and after the SELECT ?


It sounds like your table has the IDENTITY property. In such case, use
the function scope_identity() to retrieve last generated ID value.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Mulit table insert

Can some one point me in the right direction on this. I am trying to insert data into two different table. The problem is, even though table 2 had a "not null" on it's primary, the insert command still allow it to be null.

Here is what I am trying to do. When I click the submit button on my web app, it should send this information in for to table 2. The procedure should then pull the id2 and and enter it into the table as FK to table 1.

Like I said before, the id2 doesn't seem to pass any data because the procedure is passing a null, even thout a set the pk value to not null.


DECLARE @.identHolder int
DECLARE @.ID2 int

BEGIN TRANSACTION
IF NOT EXISTS (SELECT ID2 FROM [tbl2] WHERE ID1 = @.ID2)
BEGIN
(SELECT 2ID FROM [tbl2] WHERE ID1 = @.ID1) SET @.identHolder = @.@.Identity

END
ELSE
BEGIN
INSERT INTO [t2] ([fName], [lName], [shift], [userName], [emailAdd])
VALUES ( @.fName, @.lName, @.shift, @.userName, @.emailAdd) SET @.identHolder = @.@.Identity

END
COMMIT

SET @.ID2 = (@.@.Identity)
INSERT INTO [tbl1]([ID1], [ID2], [event], [removed])
VALUES (@.ID1, @.ID2, @.event, @.removed)I suggest you go back to old school debugging.
Stick a handful of

PRINT @.ID2
--Actually, you'll probably need:
PRINT Convert(varchar, ID2)

And watch the value.
Should the value perhaps be before the COMMIT?|||I figured it out. The "IF Not Exist" needed to be "If exist". I was telling the DB to check for a record but instead of creating the record if not exist, I was selecting it. Once I change that it work. I think I had to fix a datatype too.

Thank you.|||You should also put some error handling after the INSERT to rollback (or whatever) in case of an error (constraint, FK, unique index etc). Use the @.@.ERROR function in SQL Server 2000 and TRY...CATCH in SQL Server 2005.

Many people seems to forget about TSQL error handling.
What should happen if a statement fails? If xact_abort is on the transaction is rolled back and the execution of the batch stops, but if xact_abort is off the transaction remains open and then the batch continues to execute. This can and will lead to lots of problems.|||Do you know of a good site I can go to where I can learn how to write it? I just starting to learn TSQL and not to sure how I would go about creating a proper @.@.ERROR message. Does the @.@.ERROR have to return a value to the application or does it stay with in the db? Thank for the heads up.|||Are you using 2000 or 2005?

@.@.ERROR is the only way in 2000, but as I said, in 2005 you should rather use TRY...CATCH.|||and you probably should use scope_identit() instead|||Linky! (http://codebetter.com/blogs/john.papa/archive/2006/04/07/142503.aspx)
I did not know that :)|||Are you using 2000 or 2005?

@.@.ERROR is the only way in 2000, but as I said, in 2005 you should rather use TRY...CATCH.

I am using 2000

Friday, March 9, 2012

MSSQL2k retrive data from xml

Hello
I have mssql 2k there database and few XML files. I try get data from XML
files and insert into database. How to do that using DTS'
AJAHello AJA,

> I have mssql 2k there database and few XML files. I try get data
> from XML
> files and insert into database. How to do that using DTS'
Here's about a dozen ideas:
http://www.perfectxml.com/articles/xml/importxmlsql.asp
Thanks!
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/|||>> I have mssql 2k there database and few XML files. I try get data
> Here's about a dozen ideas:
> http://www.perfectxml.com/articles/xml/importxmlsql.asp
Yes i watched there and:
OPENXML does not work because to big file 10+MB or maybe anyone have idea
how to prepare_document using text variable? code which i found opened max
1,5MB xml file
Microsoft Visual Basic no have so can no make project using VB
I was intrested to use this one "DTS ActiveX Script & MSXML 4.0 DOM". I
tried, installed MSXML and copied code but it does not work.
Succesfully execution but no records in destination tables.
I have no idea what was wrong :(
Best Regards
AJA|||Hello AJA,
One thing that I'll suggest is that you get off of SQL Server 2000 DTS and
look seriously at SQL Server 2005's SSIS bits. Much better for working with
XML.
Thanks!
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/|||> One thing that I'll suggest is that you get off of SQL Server 2000 DTS and
> look seriously at SQL Server 2005's SSIS bits. Much better for working
> with XML.
The problem is I can no change MSSQL to 2005 because its not my software.
So i'm looking how to solve it in MSSQL 2k.
Best Regards
AJA|||Hello,
Check out SQLXML technology
:http://msdn2.microsoft.com/en-us/library/aa225763(SQL.80).aspx.
I hope this helps.
Regards,
--
Monica Frintu
"AJA" wrote:

> Hello
> I have mssql 2k there database and few XML files. I try get data from XM
L
> files and insert into database. How to do that using DTS'
>
> AJA
>

MSSQL2k retrive data from xml

Hello
I have mssql 2k there database and few XML files. I try get data from XML
files and insert into database. How to do that using DTS?
AJA
Hello AJA,

> I have mssql 2k there database and few XML files. I try get data
> from XML
> files and insert into database. How to do that using DTS?
Here's about a dozen ideas:
http://www.perfectxml.com/articles/xml/importxmlsql.asp
Thanks!
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/
|||>> I have mssql 2k there database and few XML files. I try get data
> Here's about a dozen ideas:
> http://www.perfectxml.com/articles/xml/importxmlsql.asp
Yes i watched there and:
OPENXML does not work because to big file 10+MB or maybe anyone have idea
how to prepare_document using text variable? code which i found opened max
1,5MB xml file
Microsoft Visual Basic no have so can no make project using VB
I was intrested to use this one "DTS ActiveX Script & MSXML 4.0 DOM". I
tried, installed MSXML and copied code but it does not work.
Succesfully execution but no records in destination tables.
I have no idea what was wrong
Best Regards
AJA
|||Hello AJA,
One thing that I'll suggest is that you get off of SQL Server 2000 DTS and
look seriously at SQL Server 2005's SSIS bits. Much better for working with
XML.
Thanks!
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/
|||> One thing that I'll suggest is that you get off of SQL Server 2000 DTS and
> look seriously at SQL Server 2005's SSIS bits. Much better for working
> with XML.
The problem is I can no change MSSQL to 2005 because its not my software.
So i'm looking how to solve it in MSSQL 2k.
Best Regards
AJA
|||Hello,
Check out SQLXML technology
:http://msdn2.microsoft.com/en-us/library/aa225763(SQL.80).aspx.
I hope this helps.
Regards,
Monica Frintu
"AJA" wrote:

> Hello
> I have mssql 2k there database and few XML files. I try get data from XML
> files and insert into database. How to do that using DTS?
>
> AJA
>

Wednesday, March 7, 2012

Mssql2000

Environment: OS-Win2K MSSQL2000
My problem:
I need to insert data from a table in MSSQL2000 to a Sybase V12.5 table.
I did a C++ program (as extended stored procedure-ESP), which runs O.K. if I start it manually.
If I start it thru a MSSQL2000 Job (defining a job, inside it is a SP and inside of it is my start of ESP), then I'm getting some errors.
This is now priority 2.
Priority 1 is:
for testing of this ESP I have to stop MSSQLSERVER service and copy the new version if ESP. And then I'm starting MSSQLSERVER service and SQLSERVERAGENT. Both are running O.K. without any events in Event Viewer.
But if I'd like to start SQL Query Analyzer I can't login into it. I'm getting an error:
Unable to connect to server:Msg 17, Level 16, State 1
[Microsoft][ODBC SQL Server Driver][TCP/IP Socekts] SQL Server does not exist or access denied"
Below are 2 files: ERRRLOG and SQLAGENT.OUT
************************************************** *********************************************
ERRORLOG
************************************************** *********************************************
2003-05-29 08:26:18.22 server Microsoft SQL Server 2000 - 8.00.194 (Intel X86)
Aug 6 2000 00:57:48
Copyright (c) 1988-2000 Microsoft Corporation
Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 3)

2003-05-29 08:26:18.32 server Copyright (C) 1988-2000 Microsoft Corporation.
2003-05-29 08:26:18.32 server All rights reserved.
2003-05-29 08:26:18.32 server Server Process ID is 828.
2003-05-29 08:26:18.32 server Logging SQL Server messages in file 'c:\MSSQL\log\ERRORLOG'.
2003-05-29 08:26:18.48 server SQL Server is starting at priority class 'normal'(1 CPU detected).
2003-05-29 08:26:19.60 server SQL Server configured for thread mode processing.
2003-05-29 08:26:19.74 server Using dynamic lock allocation. [2500] Lock Blocks, [5000] Lock Owner Blocks.
2003-05-29 08:26:19.79 server Attempting to initialize Distributed Transaction Coordinator.
2003-05-29 08:26:22.69 server Failed to obtain TransactionDispenserInterface: Result Code = 0x80004005
2003-05-29 08:26:23.16 spid3 Starting up database 'master'.
2003-05-29 08:26:27.17 server Using 'SSNETLIB.DLL' version '8.0.194'.
2003-05-29 08:26:27.17 spid5 Starting up database 'model'.
2003-05-29 08:26:27.27 spid3 Server name is 'OTCPSRV01'.
2003-05-29 08:26:27.31 spid8 Starting up database 'msdb'.
2003-05-29 08:26:27.31 spid9 Starting up database 'pubs'.
2003-05-29 08:26:27.31 spid10 Starting up database 'QA'.
2003-05-29 08:26:27.31 spid11 Starting up database 'DEVEXEC'.
2003-05-29 08:26:29.55 spid5 Clearing tempdb database.
2003-05-29 08:26:29.89 spid11 Analysis of database 'DEVEXEC' (7) is 100% complete (approximately 0 more seconds)
2003-05-29 08:26:31.21 spid10 Analysis of database 'QA' (6) is 100% complete (approximately 0 more seconds)
2003-05-29 08:26:34.20 server SQL server listening on Shared Memory.
2003-05-29 08:26:34.20 server SQL Server is ready for client connections
2003-05-29 08:26:37.49 spid5 Starting up database 'tempdb'.
2003-05-29 08:26:38.64 spid5 Analysis of database 'tempdb' (2) is 100% complete (approximately 0 more seconds)
2003-05-29 08:26:39.87 spid3 Recovery complete.
2003-05-29 08:26:58.87 spid51 Using 'xpsqlbot.dll' version '2000.80.194' to execute extended stored procedure 'xp_qv'.
2003-05-29 08:28:03.56 spid53 Using 'xplog70.dll' version '2000.80.194' to execute extended stored procedure 'xp_cmdshell'.
2003-05-29 08:28:05.23 spid53 Using 'xpstar.dll' version '2000.80.194' to execute extended stored procedure 'xp_sqlagent_enum_jobs'.

************************************************** *********************************************
SQLAGENT.OUT
************************************************** *********************************************
2003-05-29 08:26:59 - ? [100] Microsoft SQLServerAgent version 8.00.194 (x86 unicode retail build) : Process ID 1284
2003-05-29 08:26:59 - ? [101] SQL Server OTCPSRV01 version 8.00.194 (0 connection limit)
2003-05-29 08:26:59 - ? [102] SQL Server ODBC driver version 3.80.528
2003-05-29 08:26:59 - ? [103] NetLib being used by driver is DBMSSHRN.DLL; Local host server is (local)
2003-05-29 08:26:59 - ? [310] 1 processor(s) and 768 MB RAM detected
2003-05-29 08:26:59 - ? [339] Local computer is OTCPSRV01 running Windows NT 5.0 (2195) Service Pack 3
2003-05-29 08:27:02 - ? [129] SQLSERVERAGENT starting under Windows NT service control
2003-05-29 08:27:02 - + [260] Unable to start mail session (reason: No mail profile defined)
2003-05-29 08:27:02 - + [396] An idle CPU condition has not been defined - OnIdle job schedules will have no effect
2003-05-29 08:28:33 - ! [298] SQLServer Error: 17, SQL Server does not exist or access denied. [SQLSTATE 08001]
2003-05-29 08:28:33 - ! [298] SQLServer Error: 10061, ConnectionOpen (Connect()). [SQLSTATE 01000]
2003-05-29 08:28:33 - ! [382] Logon to server 'OTCPSRV01' failed (ConnAttemptCachableOp)
2003-05-29 08:28:33 - ! [298] SQLServer Error: 17, SQL Server does not exist or access denied. [SQLSTATE 08001]
2003-05-29 08:28:33 - ! [298] SQLServer Error: 10061, ConnectionOpen (Connect()). [SQLSTATE 01000]
2003-05-29 08:28:33 - ! [382] Logon to server 'OTCPSRV01' failed (ConnAttemptCachableOp)
the last 3 lines are repeating ....
The definition of Client Network Utility is O.K. ( it was good until I have started with tests)
SSNETLIB.DLL is V2000.80.194 - is it O.K. or too old for this task?

My question is - what should I do? to make SQL runable?:(May take help of this KBA (http://support.microsoft.com/default.aspx?scid=kb;en-us;Q311836&gssnb=1).|||Originally posted by Satya
May take help of this KBA (http://support.microsoft.com/default.aspx?scid=kb;en-us;Q311836&gssnb=1).

Thank you for your advice. I'll check it just now!:rolleyes: :rolleyes:|||Originally posted by Wedlechowicz
Thank you for your advice. I'll check it just now!:rolleyes: :rolleyes:

Hi Satya,

I have checked it all.
Sorry, but it doesn't work.

And it's funny, but I have set in Services the MSSQLSERV on MANUAL and after reboot that services is started!!! Why? I thought it won't be started after reboot. And there's no Job in MSSQL that could do it automatically.

What do you mean about it all?
Zbig:confused:|||Make sure to make the SQLAgent service manual too.
Start your SQL server service first and then agent service, see what error you will get. Seems your SQL server service is not started correctly. Make sure your agent service is set up correctly including the username and password.|||True, make sure to have necessary privileges for SQL services account.|||Originally posted by Satya
True, make sure to have necessary privileges for SQL services account.
Hi,
I decided to do so:
I reinstalled the whole MSSQL Server, e.g. thru it I have got the "NEW" refreshed Registry (ONLY this and nothing MORE) and all was then O.K.

Thank you for this help!
:) :p

mssql: insert into syntax

Hello
Can anyone help me translate this from access so that it can work in mssql
(i need to get next value, but cannot use identity as if row is deleted,
another must get new next column number which would be same as deleted one)
Access;
INSERT INTO table
SELECT
(IIF(code<>Null,MAX(code)+1,1) AS code,
0 AS usercode
FROM table

I tried this in mssql but will not work:
INSERT INTO table
SELECT
CASE
WHEN code IS NULL THEN 1
ELSE MAX(code)+1
END
AS code,
0 AS usercode
FROM tableHi

You may be better of using an identity column. It is not guaranteed to be
contiguous but usually is the ordinal value that is required. This is
similar to the autoincrementing number in access. See the topic "Identity
(Property)" in books online for more information.

John

"Andre" <spam@.spam.com> wrote in message news:de9g0c$ih4$1@.ss405.t-com.hr...
> Hello
> Can anyone help me translate this from access so that it can work in mssql
> (i need to get next value, but cannot use identity as if row is deleted,
> another must get new next column number which would be same as deleted
> one)
> Access;
> INSERT INTO table
> SELECT
> (IIF(code<>Null,MAX(code)+1,1) AS code,
> 0 AS usercode
> FROM table
> I tried this in mssql but will not work:
> INSERT INTO table
> SELECT
> CASE
> WHEN code IS NULL THEN 1
> ELSE MAX(code)+1
> END
> AS code,
> 0 AS usercode
> FROM table|||On Sun, 21 Aug 2005 11:02:42 +0200, Andre wrote:

(snip)
>Access;
>INSERT INTO table
>SELECT
> (IIF(code<>Null,MAX(code)+1,1) AS code,
>0 AS usercode
>FROM table

Hi Andre,

As John says: Consider using IDENTITY (the SQL Server equivalent of what
Access calls "autonumber").

If there are reason's why you can't use IDENTITY, then use

SELECT COALESCE(MAX(code), 0) + 1 AS code
FROM table

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||will try this
thx

(by the way, i mentioned I cannot use identity as it would not preserve
correct order if a middle row is deleted
and it would not allow end-user to change it)
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:6fqgg1d3f7bpim4ct0bril93j6vkedhgek@.4ax.com...
> On Sun, 21 Aug 2005 11:02:42 +0200, Andre wrote:

> If there are reason's why you can't use IDENTITY, then use
> SELECT COALESCE(MAX(code), 0) + 1 AS code
> FROM table|||On Sun, 21 Aug 2005 14:19:39 +0200, Andre wrote:

>will try this
>thx
>(by the way, i mentioned I cannot use identity as it would not preserve
>correct order if a middle row is deleted
>and it would not allow end-user to change it)

Hi Andre,

That's a logical result of the "raison d'etre" of the IDENTITY
attribute. You should use IDENTITY only to generate a unique numeric
value that can be used in place of the "real" key in foreign key
relationships. For instance, if a Foo is identified by the combination
of FooName, FooDate and FooWeight, the tables Foo and Bar *could* look
like this:

CREATE TABLE Foo
(FooName varchar(35) NOT NULL,
FooDate datetime NOT NULL,
FooWeight numeric (15,7) NOT NULL,
-- other columns,
PRIMARY KEY (FooName, FooDate, FooWeight)
)
CREATE TABLE Bar
(BarNo int NOT NULL,
FooName varchar(35) NOT NULL,
FooDate datetime NOT NULL,
FooWeight numeric (15,7) NOT NULL,
-- other columns,
PRIMARY KEY (BarNo),
FOREIGN KEY (FooName, FooDate, FooWeight)
REFERENCES Foo (FooName, FooDate, FooWeight)
ON UPDATE CASCADE
ON DELETE NO ACTION
)

Or, you could use IDENTITY to create a surrogate key and have your
tables like this:

CREATE TABLE Foo
(FooID int NOT NULL IDENTITY,
FooName varchar(35) NOT NULL,
FooDate datetime NOT NULL,
FooWeight numeric (15,7) NOT NULL,
-- other columns,
PRIMARY KEY (FooID),
UNIQUE (FooName, FooDate, FooWeight)
)
CREATE TABLE Bar
(BarNo int NOT NULL,
FooID int NOT NULL IDENTITY,
-- other columns,
PRIMARY KEY (BarNo),
FOREIGN KEY (FooID) REFERENCES Foo (FooID)
ON DELETE NO ACTION
)

This gives Bar a smaller footprint, and will speed up te joins (but at
the expense of a higher number of required joins). Note that a Foo is
still identified by it's "real" key. Also note that you might just as
well keep the "real" key as PRIMARY KEY and declare the identity column
to be UNIQUE (that will affect how your indexes look, so this is a
choice that affects performance).

An important issue to keep in mind is that the end user never sees the
identity value in this case. The end user will only see the "real" key,
as determined when investigating the business' information needs.

Your mention of preserving order when rows are deleted makes me think
that you want to use IDENTITY to get a ranking. In that case: don't. The
only thing MS guarantees about IDENITY is that it will be a unique value
in it's table (proivided you never override the generated values or
reset the seed). If you need a rank, you can either:
a) Compute it whenever you query the data. Use a view if you don't want
to retype the same query logic over and over again, or
b) Compute and store it; recompute ranks after each modification; this
one is dangerous (one uncontrolled modification can ruin the scheme) and
can slow down modification operations - only use it if you query the
data (including the rank) much more often than you modify the data.

Your mention of end users changing the value makes me think that you
don't want a ranking after all - but if have no idea what you do want to
use it for. Can you explain the purpose of this? I'm asking partly out
of curiosity, partly because I have the feeling that you're about to
make an error that either you or your successor will regret - I might be
wrong (I hope so!), but if I'm not, you better change your plan now,
before it is too late!

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||I have an accounting program which I am moving to mssql.
Now, I have tables which contain various documents (bills, inputs/outputs
etc).
Each document in its group must be in order
1,2,3...
there can be no omissions.
Now, I must permit to some users to delete documents (if these have been
entered by mistake), but also to permit
them to change their numbers. But these numbers must be unique in their
respective tables.
And, when user is creating new document, program must give him next number
(serial number if you wish).

So, since user might delete a middle row, using identity would mean that he
could, later when he creates document, give it the
number he previously deleted. I could set identity to allow change, but I
don't want to.

My programs currently run on access and mysql. I am adding mssql but didn't
expect so much trouble with sql syntax
Coalesce was mentioned in previous post: it does not work
I need simple

INSERT INTO table SELECT ISNULL(MAX(fieldvalue)+1,1) AS fieldvalue FROM
table
or
INSERT INTO table SELECT MAX(fieldvalue)+1 AS fieldvalueFROM table

if this is not possible on mssql, I will have to create on insert trigger or
lock table while creating new entry and first get value, then insert it into
table (1 query, 1 insert - lock, since two users might at the same time
create new: while information fieldvalue+1 travels to first user, second
executes same query and gets same
number as first has not made insert yet)|||Hugo Kornelis (hugo@.pe_NO_rFact.in_SPAM_fo) writes:
> Your mention of preserving order when rows are deleted makes me think
> that you want to use IDENTITY to get a ranking. In that case: don't. The
> only thing MS guarantees about IDENITY is that it will be a unique value

Eh, Andr says he does not want to use IDENTITY, so you tell him not to
use it?

Anyway, if you say:

INSERT tbl (...)
SELECT ...
ORDER BY ...

and tbl has an IDENTITY column, the message I have, is indeed that there
is a guarantee that the IDENTITY values will reflect the ORDER BY clause.

However, this does not apply to SELECT INTO.

In any case, it is obvious from Andre's description of his business problem
that he should stay away from IDENTITY.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Andre (spam@.spam.com) writes:
> Coalesce was mentioned in previous post: it does not work

Please defined "does not work". Do you get an error message, do you
get unexpected result, does heaven fall down on your or what?

In any case, this seem to work:

CREATE TABLE andre (id int NOT NULL PRIMARY KEY,
somedata varchar(230) NOT NULL)
go
INSERT andre (id, somedata)
SELECT coalesce(MAX(id), 0) + 1, 'This is some data'
FROM andre
INSERT andre (id, somedata)
SELECT coalesce(MAX(id), 0) + 1, 'This is some other data'
FROM andre
INSERT andre (id, somedata)
SELECT coalesce(MAX(id), 0) + 1, 'This is any data'
FROM andre
go
SELECT * FROM andre ORDER BY id
go
DROP TABLE andre

> I need simple
> INSERT INTO table SELECT ISNULL(MAX(fieldvalue)+1,1) AS fieldvalue FROM

Since isnull() is proprietary to SQL Server, while coalesce() is
ANSI-SQL and you support other DBMS's, coalesce() would be a better
choice.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Hi

You can try it as

INSERT INTO table
SELECT ISNULL(MAX(code),0)+1, 0 FROM table

Please let me know if u have any questions

best Regards,
Chandra
http://www.SQLResource.com/
http://chanduas.blogspot.com/
------------

*** Sent via Developersdex http://www.developersdex.com ***|||Hi Andre

>From your description it sounds like you have to re-order everything if
you remove an intermediate document. This will not lead to a very
scalable application.

John|||Thank you all for help.

Problem was somewhere else:

I tried
INSERT INTO table x AS fieldx, y AS fieldy FROM table
while correct (for MSSQL obviously) is:
INSERT table (fieldx,fieldy) SELECT x,y FROM table

again, thank you for your time

p.s.: I wonder why are there such differences between sql syntax for various
databases (as in: what is the point of standard which is ignored)|||Andre (spam@.spam.com) writes:
> Thank you all for help.
> Problem was somewhere else:
> I tried
> INSERT INTO table x AS fieldx, y AS fieldy FROM table
> while correct (for MSSQL obviously) is:
> INSERT table (fieldx,fieldy) SELECT x,y FROM table

As far as I know the latter is also compliant with ANSI standards.
(Save for the fact that ANSI mandates INTO, while this is optional in
MS SQL Server.) The first syntax is something I've never seen before.
Does it work anywhere?

> p.s.: I wonder why are there such differences between sql syntax for
> various databases (as in: what is the point of standard which is
> ignored)

Indeed, just because it is the standard, does not mean that it is
implemnented everywhere. However, the basics of a regular INSERT
statement is something I would expect to work everywhere.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||On Sun, 21 Aug 2005 23:34:40 +0200, Andre wrote:

>I have an accounting program which I am moving to mssql.
>Now, I have tables which contain various documents (bills, inputs/outputs
>etc).
>Each document in its group must be in order
>1,2,3...
>there can be no omissions.
>Now, I must permit to some users to delete documents (if these have been
>entered by mistake), but also to permit
>them to change their numbers. But these numbers must be unique in their
>respective tables.
>And, when user is creating new document, program must give him next number
>(serial number if you wish).
(snip)

Hi Andre,

There are some conflicting requirements. If there may be no omissions,
than you must either not allow users to delete a document (or rather:
don't allow them to delete A ROW - if the corresponding document is
deleted, keep the row but set a column to indicate that the document is
deleted) - or you must renumber all documents each time a document is
deleted to make sure that there never are gaps. Of course, if these
numbers are visible to the user and used to identify the documents, then
renumbering them will wreak havoc to the ability to relate rows in the
database to the actual documents. And if the users don't see the
numbers, then why bother with trying to keep them without omissions?

Also, if you allow users to change the document number, you are actually
guaranteed to get omissions. Sooner or later, someone will type the
number 42 because he's a Douglas Adams fan.

If the actual requirement is to use a number that is PREFERABLY
increasing and without gaps, and that users can optionally change to
reuse the number of a deleted document, I'd say: do a SELECT MAX(..)
query in the front end; increase by one and prepopulate the number field
in your frontend with that number. The user can either accept this
default or type a different number. The number that is in the field when
the user submits his data entry is sent to the database in an INSERT ...
VALUES statement.

(snip)
>I could set identity to allow change, but I
>don't want to.

So instead, you try to create your own solution that behaves exactly as
IDENTITY after setting it to allow change, but less scalable?

(snip)
>Coalesce was mentioned in previous post: it does not work
>I need simple
>INSERT INTO table SELECT ISNULL(MAX(fieldvalue)+1,1) AS fieldvalue FROM
>table

This should work. If you replace ISNULL with COALESCE, it should still
work. If it doesn't then please provide more information.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Actually, it is only important to fetch new table entry as CODE+1
Gaps are OK if user makes them. Skipping order number of CODE by user is
also OK.
But program must always return CODE+1 when new row is added.
User may change the number to any he wishes (except existing one) and the
next new row will be +1
This, of course, is not my idea. I would forbid deleting documents (even law
requires them to be void, not deleted - we are talking about accounting
program)
but then nobody would purchase my program.

"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:ipfkg118so3erd23b2sqa65kcsbosi585f@.4ax.com...
> On Sun, 21 Aug 2005 23:34:40 +0200, Andre wrote:
> There are some conflicting requirements. If there may be no omissions,
> than you must either not allow users to delete a document (or rather:
> don't allow them to delete A ROW - if the corresponding document is
> deleted, keep the row but set a column to indicate that the document is
> deleted) - or you must renumber all documents each time a document is
> deleted to make sure that there never are gaps. Of course, if these
> numbers are visible to the user and used to identify the documents, then
> renumbering them will wreak havoc to the ability to relate rows in the
> database to the actual documents. And if the users don't see the
> numbers, then why bother with trying to keep them without omissions?
> Also, if you allow users to change the document number, you are actually
> guaranteed to get omissions. Sooner or later, someone will type the
> number 42 because he's a Douglas Adams fan.
> If the actual requirement is to use a number that is PREFERABLY
> increasing and without gaps, and that users can optionally change to
> reuse the number of a deleted document, I'd say: do a SELECT MAX(..)
> query in the front end; increase by one and prepopulate the number field
> in your frontend with that number. The user can either accept this
> default or type a different number. The number that is in the field when
> the user submits his data entry is sent to the database in an INSERT ...
> VALUES statement.|||On Tue, 23 Aug 2005 13:28:57 +0200, Andre wrote:

>Actually, it is only important to fetch new table entry as CODE+1
>Gaps are OK if user makes them. Skipping order number of CODE by user is
>also OK.
>But program must always return CODE+1 when new row is added.
>User may change the number to any he wishes (except existing one) and the
>next new row will be +1
>This, of course, is not my idea. I would forbid deleting documents (even law
>requires them to be void, not deleted - we are talking about accounting
>program)
>but then nobody would purchase my program.

Hi Andre,

I stick with my previous recommendation.

1. Fetch MAX(code)+1 with a non-locking query when opening the screen.
Either display it as default value in the code field, or keep the code
field blank.

2. When details are entered, attempt to insert the row, with code as
entered on the screen; if no value is entered, use the MAX(code)+1 from
the previous call.

3. If a row with the chosen key value exists, further action is decided
by the front end:

3a. If key was entered by user: error message.
3b. If user didn't override the default, re-insert row with MAX(code)+1
as new code; show warning message that code has been changed.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)