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

Friday, March 30, 2012

problem returning IDENTITY

Hi all,
I have a sp where I only do an insert, and am trying to return the
identity value created. Here's what my sp resemble :
...
AS
SET NOCOUNT ON
-- do the insert
DECLARE @.ret
SELECT @.ret = SCOPE_IDENTITY()
RETURN @.ret
I tried to return directly SCOPE_IDENTITY(), I also tried to change
SCOPE_IDENTITY() with @.@.IDENTITY, with and without SET NOCOUNT ON...I
don't know what to do anymore. A few times it returned always 1 and at
other times, it was always returning -1. This depended on what options
I've tried, I don't remember what situation returned what value...but
for now, written as above, it is returning -1.
thanks for your help!
ibiza wrote:

> Hi all,
> I have a sp where I only do an insert, and am trying to return the
> identity value created. Here's what my sp resemble :
> ...
> AS
> SET NOCOUNT ON
> -- do the insert
> DECLARE @.ret
> SELECT @.ret = SCOPE_IDENTITY()
> RETURN @.ret
> I tried to return directly SCOPE_IDENTITY(), I also tried to change
> SCOPE_IDENTITY() with @.@.IDENTITY, with and without SET NOCOUNT ON...I
> don't know what to do anymore. A few times it returned always 1 and at
> other times, it was always returning -1. This depended on what options
> I've tried, I don't remember what situation returned what value...but
> for now, written as above, it is returning -1.
> thanks for your help!
It isn't a good idea to use RETURN to return data from a proc. Use
RETURN for error status only: zero = OK, non-zero = error. To return
other values use an output parameter or a result set:
CREATE PROC usp_x
(@.param1 INTEGER, @.ret INTEGER OUTPUT)
AS
SET NOCOUNT ON;
SET @.ret = 123;
RETURN
GO
DECLARE @.r INTEGER;
EXEC usp_x @.param1 = 1, @.ret = @.r OUTPUT;
SELECT @.r;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
|||thank you very much for your reply. Well, it does work with an output
parameter!
And I will take note of your remark for my upcoming posts.
Thanks again!

problem returning IDENTITY

Hi all,
I have a sp where I only do an insert, and am trying to return the
identity value created. Here's what my sp resemble :
...
AS
SET NOCOUNT ON
-- do the insert
DECLARE @.ret
SELECT @.ret = SCOPE_IDENTITY()
RETURN @.ret
I tried to return directly SCOPE_IDENTITY(), I also tried to change
SCOPE_IDENTITY() with @.@.IDENTITY, with and without SET NOCOUNT ON...I
don't know what to do anymore. A few times it returned always 1 and at
other times, it was always returning -1. This depended on what options
I've tried, I don't remember what situation returned what value...but
for now, written as above, it is returning -1.
thanks for your help!ibiza wrote:
> Hi all,
> I have a sp where I only do an insert, and am trying to return the
> identity value created. Here's what my sp resemble :
> ...
> AS
> SET NOCOUNT ON
> -- do the insert
> DECLARE @.ret
> SELECT @.ret = SCOPE_IDENTITY()
> RETURN @.ret
> I tried to return directly SCOPE_IDENTITY(), I also tried to change
> SCOPE_IDENTITY() with @.@.IDENTITY, with and without SET NOCOUNT ON...I
> don't know what to do anymore. A few times it returned always 1 and at
> other times, it was always returning -1. This depended on what options
> I've tried, I don't remember what situation returned what value...but
> for now, written as above, it is returning -1.
> thanks for your help!
It isn't a good idea to use RETURN to return data from a proc. Use
RETURN for error status only: zero = OK, non-zero = error. To return
other values use an output parameter or a result set:
CREATE PROC usp_x
(@.param1 INTEGER, @.ret INTEGER OUTPUT)
AS
SET NOCOUNT ON;
SET @.ret = 123;
RETURN
GO
DECLARE @.r INTEGER;
EXEC usp_x @.param1 = 1, @.ret = @.r OUTPUT;
SELECT @.r;
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||thank you very much for your reply. Well, it does work with an output
parameter!
And I will take note of your remark for my upcoming posts.
Thanks again! :)

problem returning IDENTITY

Hi all,
I have a sp where I only do an insert, and am trying to return the
identity value created. Here's what my sp resemble :
...
AS
SET NOCOUNT ON
-- do the insert
DECLARE @.ret
SELECT @.ret = SCOPE_IDENTITY()
RETURN @.ret
I tried to return directly SCOPE_IDENTITY(), I also tried to change
SCOPE_IDENTITY() with @.@.IDENTITY, with and without SET NOCOUNT ON...I
don't know what to do anymore. A few times it returned always 1 and at
other times, it was always returning -1. This depended on what options
I've tried, I don't remember what situation returned what value...but
for now, written as above, it is returning -1.
thanks for your help!ibiza wrote:

> Hi all,
> I have a sp where I only do an insert, and am trying to return the
> identity value created. Here's what my sp resemble :
> ...
> AS
> SET NOCOUNT ON
> -- do the insert
> DECLARE @.ret
> SELECT @.ret = SCOPE_IDENTITY()
> RETURN @.ret
> I tried to return directly SCOPE_IDENTITY(), I also tried to change
> SCOPE_IDENTITY() with @.@.IDENTITY, with and without SET NOCOUNT ON...I
> don't know what to do anymore. A few times it returned always 1 and at
> other times, it was always returning -1. This depended on what options
> I've tried, I don't remember what situation returned what value...but
> for now, written as above, it is returning -1.
> thanks for your help!
It isn't a good idea to use RETURN to return data from a proc. Use
RETURN for error status only: zero = OK, non-zero = error. To return
other values use an output parameter or a result set:
CREATE PROC usp_x
(@.param1 INTEGER, @.ret INTEGER OUTPUT)
AS
SET NOCOUNT ON;
SET @.ret = 123;
RETURN
GO
DECLARE @.r INTEGER;
EXEC usp_x @.param1 = 1, @.ret = @.r OUTPUT;
SELECT @.r;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||thank you very much for your reply. Well, it does work with an output
parameter!
And I will take note of your remark for my upcoming posts.
Thanks again!

Wednesday, March 28, 2012

Problem Retrieving @@Identity when inside a transaction.

I'm using transactions with my SqlConnection ( sqlConnection.BeginTransaction() ).
I do an Insert into my User table, and then subsequently use thegenerated identity ( via @.@.identity ) to make an insert into anothertable. The foreign key relationship is dependant on the generatedidentity. For some reason with transactions, I can't retrieve theinsert identity (it always returns as 1). However, I need theinserts to be under a transaction so that one cannot succeed while theother fails. Does anyone know a way around this problem?
So heres a simplefied explanation of what I'm trying to do:
Begin Transaction
Insert into User Table
Retrieve Inserted Identity (userID) via @.@.Identity
Insert into UserContact table, using userID as the foreign key.
Commit Transaction.
Because of the transaction, userID is 1, therefore an insert cannot bemade into the UserContact table because of the foreign key constraint.
I need this to be a transaction in case one or the other fails. Any ideas??


Try using Scope_Identity() instead of @.@.IDENTITY and see if that solvesyour problem. Scope_Identity will give you the last identityvalue generated in your current scope.
|||I tried using Scope_Identity() and I'm getting the exact same problem.
|||I can tell you that I just tried out your scenario and it worked withno problem for me. I tried it both wrapped in a transaction andnot. So there is something particular about your code that iscausing the problem. Could you post it here?
|||Fixed it. Had nothing to do with transactions. Stupid error on my part.
It seems as though I forgot to encapsulate my sql insert procedure in aBegin / End block, so that when I performed an insert it returned 1instead of the @.@.Identity which was on the next line.
Thanks for trying to help! Much appreciated =D
|||I'm glad you got it sorted. Be sure to use Scope_Identity()instead of @.@.IDENTITY. If at some point in the future, e.g., atrigger is added to your table which inserts a record into some table,@.@.IDENTITY will contain the Identity value of that inserted record, andthat's not what you want.

Wednesday, March 21, 2012

Problem performing remote queries

I am trying to a simple insert statement from a remote application
against a sql server 2005 database. To fix the problem I was having,
I had to grant the Login I was using the role of sysadmin. However I
don't want this user to have that kind of control, what would be the
best role to allow the user full access(including remoting) to only
one particular database?rhaazy pisze:

Quote:

Originally Posted by

I am trying to a simple insert statement from a remote application
against a sql server 2005 database. To fix the problem I was having,
I had to grant the Login I was using the role of sysadmin. However I
don't want this user to have that kind of control, what would be the
best role to allow the user full access(including remoting) to only
one particular database?


First, tell us what the problem was (provide an error message or other
details).

You can configure detailed permissions in SQL Server 2005, granting
sysadmin server role is far too much. Grant the login only enumerated
permissions that are essential to perform certain tasks (simple insert
in your case). Here is an T-SQL statement to do it:

GRANT INSERT ON your_table TO some_user;

Of course there are alternate solutions - e.g. database role
(db_datawriter), but try that one I mentioned above.

--
Best regards,
Marcin Guzowski
http://guzowski.info|||The error message is simply that my user didn't have permission to
execute the statement.

I would like to be able to grant the user insert, update, delete,
select on all tables in a particular database.(remotely or local, both
situations are possible)

How would I do this?|||rhaazy pisze:

Quote:

Originally Posted by

The error message is simply that my user didn't have permission to
execute the statement.
>
I would like to be able to grant the user insert, update, delete,
select on all tables in a particular database.(remotely or local, both
situations are possible)
>
How would I do this?


Permissions are assigned to logins/users and there is no difference
between remote and local scenario.

If you want all DML operations granted on all tables in particular
database, simply grant two database roles to your database user:

USE your_database;
GO
EXEC sp_addrolemember N'db_datareader', N'database_user';
GO
EXEC sp_addrolemember N'db_datawriter', N'database_user';
GO

--
Best regards,
Marcin Guzowski
http://guzowski.info|||As it turns out the db_owner is a more likely canidate for the level
of power I wish to give the user.

So what I need to do is add to my database install script, after I add
the user to the database, i need to grant Database Role Membership
(db_owner) for the database ClientScan for the user CSAdmin

exec sp_addlogin 'CSAdmin', 'pwd'

USE ClientScan
exec sp_adduser 'CSAdmin'

exec sp_addrolemember db_owner, CSAdmin

If there is anything wrong with my syntax please correct it.|||rhaazy (rhaazy@.gmail.com) writes:

Quote:

Originally Posted by

As it turns out the db_owner is a more likely canidate for the level
of power I wish to give the user.
>
So what I need to do is add to my database install script, after I add
the user to the database, i need to grant Database Role Membership
(db_owner) for the database ClientScan for the user CSAdmin
>
exec sp_addlogin 'CSAdmin', 'pwd'
>
USE ClientScan
exec sp_adduser 'CSAdmin'
>
exec sp_addrolemember db_owner, CSAdmin
>
If there is anything wrong with my syntax please correct it.


Since you are on SQL 2005, I would suggest that you use CREATE LOGIN
and CREATE USER rather than sp_adduser and sp_addlogin.

Note that there is a difference between CREATE USER and sp_adduser: the
latter will create a schema called CSAdmin and make that the default
schema for CSAdmin. If you only use CREATE USER, CSAdmin's default schema
will be dbo, and no schema CSAdmin will be created.

--
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.mspxsql

Problem Oracle with \ and and

Hello for all, I'm a new user and my English isn't very good .. sorry!
I have a problem with an INSERT in Oracle, the code tha I inserd is:

INSERT INTO Schema VALUES(schema_seq.nextval,C:\Documents and Settings\Laura\Desktop\Tesi\File_OGaggi)

the error is:

Error: ORA-00911: invalid character

[Executed: 13/11/03 10.31.25 GMT ] [Execution: 0/ms]

I think that the problems are '\' and the word 'and'. Someone know what can I do? Thank you, by by,

Laura.It seems to me that You have quoted Your string with the wrong character ()

You must use ' instead.sql

Tuesday, March 20, 2012

Problem on insert using stored procedure

Here is my problem on SQL Server SP3a.
I have a table that reach more than 2 millions rows. My primary key is an
identity column.
From a Java program I'm calling a strored procedure to insert a new row in
that table and to get back the id of the new row using the scope_identity()
function.
I log the id returned by the first stored procedure and to ensure the line
has been added I call a second stored procedure to look if my line exists in
the table. That request returns a line and when I call a request from SQL
Server enterprise manager on my id I get no line in my table.
I really don't understand what can be my problem because it's not reccurent,
most of the time it's work fine. It seems that the first transaction is
sometimes rolled back by the systems.
If someone has an idea...
Stored procedure 1 to INSERT:
=============================
CREATE procedure SetIndFpsLogWeb
@.F_WobNum varchar(40)='' ,
@.codeuser varchar(30)='' ,
@.datedebutetat varchar(20)='',
@.datefinetat varchar(20)='',
@.datereception varchar(20)='',
@.datecreationdossier varchar(20)='',
@.numeroenregistrement varchar(16)='',
@.activites varchar(20)='' ,
@.produit varchar(4)='' ,
@.do varchar(4)='' ,
@.idclient varchar(12)='',
@.etatdossier varchar(2)='',
@.mediaentree varchar(4)='',
@.mediasortie varchar(4)='',
@.datefindossier varchar(20)='',
@.segmentclient varchar(12)='',
@.actions varchar(50)='' ,
@.etatexportdata varchar(1)='',
@.numeroenregistrementpli varchar(20)='' ,
@.taches varchar(50)='' ,
@.languecontactentrant varchar(4)='' ,
@.languecommunication varchar(4)='',
@.pays varchar(4)='' ,
@.datefinprevisionnelle varchar(20)='' ,
@.datelimitetraitement varchar(20)=''
AS
begin transaction
IF (@.numeroenregistrement <> '' AND @.numeroenregistrementpli ='' )
BEGIN
SET @.numeroenregistrementpli = @.numeroenregistrement
END
IF (@.actions<> '' )
BEGIN
if( SUBSTRING(@.actions, 1,1)=';')
BEGIN
SET @.actions = SUBSTRING(@.actions, 2, LEN(@.actions))
END
END
IF (@.taches<> '' )
BEGIN
if( SUBSTRING(@.taches, 1,1)=';')
BEGIN
SET @.taches = SUBSTRING(@.taches, 2, LEN(@.taches))
END
END
IF (@.activites<> '' )
BEGIN
if( SUBSTRING(@.activites, 1,1)=';')
BEGIN
SET @.activites= SUBSTRING(@.activites, 2, LEN(@.activites))
END
END
INSERT INTO ind_fps (
F_WobNum,
codeuser,
datedebutetat,
datefinetat,
datereception,
datecreationdossier,
numeroenregistrement,
activites,
produit,
do,
idclient,
etatdossier,
mediaentree,
mediasortie,
datefindossier,
segmentclient,
actions,
etatexportdata,
numeroenregistrementpli,
taches,
languecontactentrant,
languecommunication,
pays,
datefinprevisionnelle,
datelimitetraitement)
VALUES (
@.F_WobNum,
@.codeuser,
@.datedebutetat,
@.datefinetat,
@.datereception,
@.datecreationdossier,
@.numeroenregistrement,
@.activites,
@.produit,
@.do,
@.idclient,
@.etatdossier,
@.mediaentree,
@.mediasortie,
@.datefindossier,
@.segmentclient,
@.actions,
@.etatexportdata,
@.numeroenregistrementpli,
@.taches,
@.languecontactentrant,
@.languecommunication,
@.pays,
@.datefinprevisionnelle,
@.datelimitetraitement)
declare @.return varchar(500)
if @.@.error <> 0
begin
set @.return = 'ERROR : ' + cast(@.@.error as varchar)
rollback tran
end
else
begin
set @.return = scope_identity()
commit tran
end
select @.return
GO
Stored procedure 2 to GET:
==========================
CREATE procedure dbo.GetIndFpsInfosById
@.indfps_id varchar(20) = ''
as
begin transaction
SELECT *
FROM [ind_fps]
WHERE id = @.indfps_id
commit transaction
GO
Do not use a transaction in the second sp and use "set nocount on" in both
sps, as the first statement.
AMB
"edemasi" wrote:

> Here is my problem on SQL Server SP3a.
> I have a table that reach more than 2 millions rows. My primary key is an
> identity column.
> From a Java program I'm calling a strored procedure to insert a new row in
> that table and to get back the id of the new row using the scope_identity()
> function.
> I log the id returned by the first stored procedure and to ensure the line
> has been added I call a second stored procedure to look if my line exists in
> the table. That request returns a line and when I call a request from SQL
> Server enterprise manager on my id I get no line in my table.
> I really don't understand what can be my problem because it's not reccurent,
> most of the time it's work fine. It seems that the first transaction is
> sometimes rolled back by the systems.
> If someone has an idea...
> Stored procedure 1 to INSERT:
> =============================
> CREATE procedure SetIndFpsLogWeb
> @.F_WobNum varchar(40)='' ,
> @.codeuser varchar(30)='' ,
> @.datedebutetat varchar(20)='',
> @.datefinetat varchar(20)='',
> @.datereception varchar(20)='',
> @.datecreationdossier varchar(20)='',
> @.numeroenregistrement varchar(16)='',
> @.activites varchar(20)='' ,
> @.produit varchar(4)='' ,
> @.do varchar(4)='' ,
> @.idclient varchar(12)='',
> @.etatdossier varchar(2)='',
> @.mediaentree varchar(4)='',
> @.mediasortie varchar(4)='',
> @.datefindossier varchar(20)='',
> @.segmentclient varchar(12)='',
> @.actions varchar(50)='' ,
> @.etatexportdata varchar(1)='',
> @.numeroenregistrementpli varchar(20)='' ,
> @.taches varchar(50)='' ,
> @.languecontactentrant varchar(4)='' ,
> @.languecommunication varchar(4)='',
> @.pays varchar(4)='' ,
> @.datefinprevisionnelle varchar(20)='' ,
> @.datelimitetraitement varchar(20)=''
> AS
>
> begin transaction
> IF (@.numeroenregistrement <> '' AND @.numeroenregistrementpli ='' )
> BEGIN
> SET @.numeroenregistrementpli = @.numeroenregistrement
> END
> IF (@.actions<> '' )
> BEGIN
> if( SUBSTRING(@.actions, 1,1)=';')
> BEGIN
> SET @.actions = SUBSTRING(@.actions, 2, LEN(@.actions))
> END
> END
> IF (@.taches<> '' )
> BEGIN
> if( SUBSTRING(@.taches, 1,1)=';')
> BEGIN
> SET @.taches = SUBSTRING(@.taches, 2, LEN(@.taches))
> END
> END
> IF (@.activites<> '' )
> BEGIN
> if( SUBSTRING(@.activites, 1,1)=';')
> BEGIN
> SET @.activites= SUBSTRING(@.activites, 2, LEN(@.activites))
> END
> END
> INSERT INTO ind_fps (
> F_WobNum,
> codeuser,
> datedebutetat,
> datefinetat,
> datereception,
> datecreationdossier,
> numeroenregistrement,
> activites,
> produit,
> do,
> idclient,
> etatdossier,
> mediaentree,
> mediasortie,
> datefindossier,
> segmentclient,
> actions,
> etatexportdata,
> numeroenregistrementpli,
> taches,
> languecontactentrant,
> languecommunication,
> pays,
> datefinprevisionnelle,
> datelimitetraitement)
> VALUES (
> @.F_WobNum,
> @.codeuser,
> @.datedebutetat,
> @.datefinetat,
> @.datereception,
> @.datecreationdossier,
> @.numeroenregistrement,
> @.activites,
> @.produit,
> @.do,
> @.idclient,
> @.etatdossier,
> @.mediaentree,
> @.mediasortie,
> @.datefindossier,
> @.segmentclient,
> @.actions,
> @.etatexportdata,
> @.numeroenregistrementpli,
> @.taches,
> @.languecontactentrant,
> @.languecommunication,
> @.pays,
> @.datefinprevisionnelle,
> @.datelimitetraitement)
> declare @.return varchar(500)
> if @.@.error <> 0
> begin
> set @.return = 'ERROR : ' + cast(@.@.error as varchar)
> rollback tran
> end
> else
> begin
> set @.return = scope_identity()
> commit tran
> end
> select @.return
> GO
> Stored procedure 2 to GET:
> ==========================
> CREATE procedure dbo.GetIndFpsInfosById
> @.indfps_id varchar(20) = ''
> as
> begin transaction
> SELECT *
> FROM [ind_fps]
> WHERE id = @.indfps_id
> commit transaction
> GO
>

Problem on insert using stored procedure

Here is my problem on SQL Server SP3a.
I have a table that reach more than 2 millions rows. My primary key is an
identity column.
From a Java program I'm calling a strored procedure to insert a new row in
that table and to get back the id of the new row using the scope_identity()
function.
I log the id returned by the first stored procedure and to ensure the line
has been added I call a second stored procedure to look if my line exists in
the table. That request returns a line and when I call a request from SQL
Server enterprise manager on my id I get no line in my table.
I really don't understand what can be my problem because it's not reccurent,
most of the time it's work fine. It seems that the first transaction is
sometimes rolled back by the systems.
If someone has an idea...
Stored procedure 1 to INSERT:
============================= CREATE procedure SetIndFpsLogWeb
@.F_WobNum varchar(40)='' ,
@.codeuser varchar(30)='' ,
@.datedebutetat varchar(20)='',
@.datefinetat varchar(20)='',
@.datereception varchar(20)='',
@.datecreationdossier varchar(20)='',
@.numeroenregistrement varchar(16)='',
@.activites varchar(20)='' ,
@.produit varchar(4)='' ,
@.do varchar(4)='' ,
@.idclient varchar(12)='',
@.etatdossier varchar(2)='',
@.mediaentree varchar(4)='',
@.mediasortie varchar(4)='',
@.datefindossier varchar(20)='',
@.segmentclient varchar(12)='',
@.actions varchar(50)='' ,
@.etatexportdata varchar(1)='',
@.numeroenregistrementpli varchar(20)='' ,
@.taches varchar(50)='' ,
@.languecontactentrant varchar(4)='' ,
@.languecommunication varchar(4)='',
@.pays varchar(4)='' ,
@.datefinprevisionnelle varchar(20)='' ,
@.datelimitetraitement varchar(20)=''
AS
begin transaction
IF (@.numeroenregistrement <> '' AND @.numeroenregistrementpli ='' )
BEGIN
SET @.numeroenregistrementpli = @.numeroenregistrement
END
IF (@.actions<> '' )
BEGIN
if( SUBSTRING(@.actions, 1,1)=';')
BEGIN
SET @.actions = SUBSTRING(@.actions, 2, LEN(@.actions))
END
END
IF (@.taches<> '' )
BEGIN
if( SUBSTRING(@.taches, 1,1)=';')
BEGIN
SET @.taches = SUBSTRING(@.taches, 2, LEN(@.taches))
END
END
IF (@.activites<> '' )
BEGIN
if( SUBSTRING(@.activites, 1,1)=';')
BEGIN
SET @.activites= SUBSTRING(@.activites, 2, LEN(@.activites))
END
END
INSERT INTO ind_fps (
F_WobNum,
codeuser,
datedebutetat,
datefinetat,
datereception,
datecreationdossier,
numeroenregistrement,
activites,
produit,
do,
idclient,
etatdossier,
mediaentree,
mediasortie,
datefindossier,
segmentclient,
actions,
etatexportdata,
numeroenregistrementpli,
taches,
languecontactentrant,
languecommunication,
pays,
datefinprevisionnelle,
datelimitetraitement)
VALUES (
@.F_WobNum,
@.codeuser,
@.datedebutetat,
@.datefinetat,
@.datereception,
@.datecreationdossier,
@.numeroenregistrement,
@.activites,
@.produit,
@.do,
@.idclient,
@.etatdossier,
@.mediaentree,
@.mediasortie,
@.datefindossier,
@.segmentclient,
@.actions,
@.etatexportdata,
@.numeroenregistrementpli,
@.taches,
@.languecontactentrant,
@.languecommunication,
@.pays,
@.datefinprevisionnelle,
@.datelimitetraitement)
declare @.return varchar(500)
if @.@.error <> 0
begin
set @.return = 'ERROR : ' + cast(@.@.error as varchar)
rollback tran
end
else
begin
set @.return = scope_identity()
commit tran
end
select @.return
GO
Stored procedure 2 to GET:
==========================
CREATE procedure dbo.GetIndFpsInfosById
@.indfps_id varchar(20) = ''
as
begin transaction
SELECT *
FROM [ind_fps]
WHERE id = @.indfps_id
commit transaction
GODo not use a transaction in the second sp and use "set nocount on" in both
sps, as the first statement.
AMB
"edemasi" wrote:
> Here is my problem on SQL Server SP3a.
> I have a table that reach more than 2 millions rows. My primary key is an
> identity column.
> From a Java program I'm calling a strored procedure to insert a new row in
> that table and to get back the id of the new row using the scope_identity()
> function.
> I log the id returned by the first stored procedure and to ensure the line
> has been added I call a second stored procedure to look if my line exists in
> the table. That request returns a line and when I call a request from SQL
> Server enterprise manager on my id I get no line in my table.
> I really don't understand what can be my problem because it's not reccurent,
> most of the time it's work fine. It seems that the first transaction is
> sometimes rolled back by the systems.
> If someone has an idea...
> Stored procedure 1 to INSERT:
> =============================> CREATE procedure SetIndFpsLogWeb
> @.F_WobNum varchar(40)='' ,
> @.codeuser varchar(30)='' ,
> @.datedebutetat varchar(20)='',
> @.datefinetat varchar(20)='',
> @.datereception varchar(20)='',
> @.datecreationdossier varchar(20)='',
> @.numeroenregistrement varchar(16)='',
> @.activites varchar(20)='' ,
> @.produit varchar(4)='' ,
> @.do varchar(4)='' ,
> @.idclient varchar(12)='',
> @.etatdossier varchar(2)='',
> @.mediaentree varchar(4)='',
> @.mediasortie varchar(4)='',
> @.datefindossier varchar(20)='',
> @.segmentclient varchar(12)='',
> @.actions varchar(50)='' ,
> @.etatexportdata varchar(1)='',
> @.numeroenregistrementpli varchar(20)='' ,
> @.taches varchar(50)='' ,
> @.languecontactentrant varchar(4)='' ,
> @.languecommunication varchar(4)='',
> @.pays varchar(4)='' ,
> @.datefinprevisionnelle varchar(20)='' ,
> @.datelimitetraitement varchar(20)=''
> AS
>
> begin transaction
> IF (@.numeroenregistrement <> '' AND @.numeroenregistrementpli ='' )
> BEGIN
> SET @.numeroenregistrementpli = @.numeroenregistrement
> END
> IF (@.actions<> '' )
> BEGIN
> if( SUBSTRING(@.actions, 1,1)=';')
> BEGIN
> SET @.actions = SUBSTRING(@.actions, 2, LEN(@.actions))
> END
> END
> IF (@.taches<> '' )
> BEGIN
> if( SUBSTRING(@.taches, 1,1)=';')
> BEGIN
> SET @.taches = SUBSTRING(@.taches, 2, LEN(@.taches))
> END
> END
> IF (@.activites<> '' )
> BEGIN
> if( SUBSTRING(@.activites, 1,1)=';')
> BEGIN
> SET @.activites= SUBSTRING(@.activites, 2, LEN(@.activites))
> END
> END
> INSERT INTO ind_fps (
> F_WobNum,
> codeuser,
> datedebutetat,
> datefinetat,
> datereception,
> datecreationdossier,
> numeroenregistrement,
> activites,
> produit,
> do,
> idclient,
> etatdossier,
> mediaentree,
> mediasortie,
> datefindossier,
> segmentclient,
> actions,
> etatexportdata,
> numeroenregistrementpli,
> taches,
> languecontactentrant,
> languecommunication,
> pays,
> datefinprevisionnelle,
> datelimitetraitement)
> VALUES (
> @.F_WobNum,
> @.codeuser,
> @.datedebutetat,
> @.datefinetat,
> @.datereception,
> @.datecreationdossier,
> @.numeroenregistrement,
> @.activites,
> @.produit,
> @.do,
> @.idclient,
> @.etatdossier,
> @.mediaentree,
> @.mediasortie,
> @.datefindossier,
> @.segmentclient,
> @.actions,
> @.etatexportdata,
> @.numeroenregistrementpli,
> @.taches,
> @.languecontactentrant,
> @.languecommunication,
> @.pays,
> @.datefinprevisionnelle,
> @.datelimitetraitement)
> declare @.return varchar(500)
> if @.@.error <> 0
> begin
> set @.return = 'ERROR : ' + cast(@.@.error as varchar)
> rollback tran
> end
> else
> begin
> set @.return = scope_identity()
> commit tran
> end
> select @.return
> GO
> Stored procedure 2 to GET:
> ==========================> CREATE procedure dbo.GetIndFpsInfosById
> @.indfps_id varchar(20) = ''
> as
> begin transaction
> SELECT *
> FROM [ind_fps]
> WHERE id = @.indfps_id
> commit transaction
> GO
>

Problem on insert using stored procedure

Here is my problem on SQL Server SP3a.
I have a table that reach more than 2 millions rows. My primary key is an
identity column.
From a Java program I'm calling a strored procedure to insert a new row in
that table and to get back the id of the new row using the scope_identity()
function.
I log the id returned by the first stored procedure and to ensure the line
has been added I call a second stored procedure to look if my line exists in
the table. That request returns a line and when I call a request from SQL
Server enterprise manager on my id I get no line in my table.
I really don't understand what can be my problem because it's not reccurent,
most of the time it's work fine. It seems that the first transaction is
sometimes rolled back by the systems.
If someone has an idea...
Stored procedure 1 to INSERT:
=============================
CREATE procedure SetIndFpsLogWeb
@.F_WobNum varchar(40)='' ,
@.codeuser varchar(30)='' ,
@.datedebutetat varchar(20)='',
@.datefinetat varchar(20)='',
@.datereception varchar(20)='',
@.datecreationdossier varchar(20)='',
@.numeroenregistrement varchar(16)='',
@.activites varchar(20)='' ,
@.produit varchar(4)='' ,
@.do varchar(4)='' ,
@.idclient varchar(12)='',
@.etatdossier varchar(2)='',
@.mediaentree varchar(4)='',
@.mediasortie varchar(4)='',
@.datefindossier varchar(20)='',
@.segmentclient varchar(12)='',
@.actions varchar(50)='' ,
@.etatexportdata varchar(1)='',
@.numeroenregistrementpli varchar(20)='' ,
@.taches varchar(50)='' ,
@.languecontactentrant varchar(4)='' ,
@.languecommunication varchar(4)='',
@.pays varchar(4)='' ,
@.datefinprevisionnelle varchar(20)='' ,
@.datelimitetraitement varchar(20)=''
AS
begin transaction
IF (@.numeroenregistrement <> '' AND @.numeroenregistrementpli ='' )
BEGIN
SET @.numeroenregistrementpli = @.numeroenregistrement
END
IF (@.actions<> '' )
BEGIN
if( SUBSTRING(@.actions, 1,1)=';')
BEGIN
SET @.actions = SUBSTRING(@.actions, 2, LEN(@.actions))
END
END
IF (@.taches<> '' )
BEGIN
if( SUBSTRING(@.taches, 1,1)=';')
BEGIN
SET @.taches = SUBSTRING(@.taches, 2, LEN(@.taches))
END
END
IF (@.activites<> '' )
BEGIN
if( SUBSTRING(@.activites, 1,1)=';')
BEGIN
SET @.activites= SUBSTRING(@.activites, 2, LEN(@.activites))
END
END
INSERT INTO ind_fps (
F_WobNum,
codeuser,
datedebutetat,
datefinetat,
datereception,
datecreationdossier,
numeroenregistrement,
activites,
produit,
do,
idclient,
etatdossier,
mediaentree,
mediasortie,
datefindossier,
segmentclient,
actions,
etatexportdata,
numeroenregistrementpli,
taches,
languecontactentrant,
languecommunication,
pays,
datefinprevisionnelle,
datelimitetraitement)
VALUES (
@.F_WobNum,
@.codeuser,
@.datedebutetat,
@.datefinetat,
@.datereception,
@.datecreationdossier,
@.numeroenregistrement,
@.activites,
@.produit,
@.do,
@.idclient,
@.etatdossier,
@.mediaentree,
@.mediasortie,
@.datefindossier,
@.segmentclient,
@.actions,
@.etatexportdata,
@.numeroenregistrementpli,
@.taches,
@.languecontactentrant,
@.languecommunication,
@.pays,
@.datefinprevisionnelle,
@.datelimitetraitement)
declare @.return varchar(500)
if @.@.error <> 0
begin
set @.return = 'ERROR : ' + cast(@.@.error as varchar)
rollback tran
end
else
begin
set @.return = scope_identity()
commit tran
end
select @.return
GO
Stored procedure 2 to GET:
==========================
CREATE procedure dbo.GetIndFpsInfosById
@.indfps_id varchar(20) = ''
as
begin transaction
SELECT *
FROM [ind_fps]
WHERE id = @.indfps_id
commit transaction
GODo not use a transaction in the second sp and use "set nocount on" in both
sps, as the first statement.
AMB
"edemasi" wrote:

> Here is my problem on SQL Server SP3a.
> I have a table that reach more than 2 millions rows. My primary key is an
> identity column.
> From a Java program I'm calling a strored procedure to insert a new row in
> that table and to get back the id of the new row using the scope_identity(
)
> function.
> I log the id returned by the first stored procedure and to ensure the line
> has been added I call a second stored procedure to look if my line exists
in
> the table. That request returns a line and when I call a request from SQL
> Server enterprise manager on my id I get no line in my table.
> I really don't understand what can be my problem because it's not reccuren
t,
> most of the time it's work fine. It seems that the first transaction is
> sometimes rolled back by the systems.
> If someone has an idea...
> Stored procedure 1 to INSERT:
> =============================
> CREATE procedure SetIndFpsLogWeb
> @.F_WobNum varchar(40)='' ,
> @.codeuser varchar(30)='' ,
> @.datedebutetat varchar(20)='',
> @.datefinetat varchar(20)='',
> @.datereception varchar(20)='',
> @.datecreationdossier varchar(20)='',
> @.numeroenregistrement varchar(16)='',
> @.activites varchar(20)='' ,
> @.produit varchar(4)='' ,
> @.do varchar(4)='' ,
> @.idclient varchar(12)='',
> @.etatdossier varchar(2)='',
> @.mediaentree varchar(4)='',
> @.mediasortie varchar(4)='',
> @.datefindossier varchar(20)='',
> @.segmentclient varchar(12)='',
> @.actions varchar(50)='' ,
> @.etatexportdata varchar(1)='',
> @.numeroenregistrementpli varchar(20)='' ,
> @.taches varchar(50)='' ,
> @.languecontactentrant varchar(4)='' ,
> @.languecommunication varchar(4)='',
> @.pays varchar(4)='' ,
> @.datefinprevisionnelle varchar(20)='' ,
> @.datelimitetraitement varchar(20)=''
> AS
>
> begin transaction
> IF (@.numeroenregistrement <> '' AND @.numeroenregistrementpli ='' )
> BEGIN
> SET @.numeroenregistrementpli = @.numeroenregistrement
> END
> IF (@.actions<> '' )
> BEGIN
> if( SUBSTRING(@.actions, 1,1)=';')
> BEGIN
> SET @.actions = SUBSTRING(@.actions, 2, LEN(@.actions))
> END
> END
> IF (@.taches<> '' )
> BEGIN
> if( SUBSTRING(@.taches, 1,1)=';')
> BEGIN
> SET @.taches = SUBSTRING(@.taches, 2, LEN(@.taches))
> END
> END
> IF (@.activites<> '' )
> BEGIN
> if( SUBSTRING(@.activites, 1,1)=';')
> BEGIN
> SET @.activites= SUBSTRING(@.activites, 2, LEN(@.activites))
> END
> END
> INSERT INTO ind_fps (
> F_WobNum,
> codeuser,
> datedebutetat,
> datefinetat,
> datereception,
> datecreationdossier,
> numeroenregistrement,
> activites,
> produit,
> do,
> idclient,
> etatdossier,
> mediaentree,
> mediasortie,
> datefindossier,
> segmentclient,
> actions,
> etatexportdata,
> numeroenregistrementpli,
> taches,
> languecontactentrant,
> languecommunication,
> pays,
> datefinprevisionnelle,
> datelimitetraitement)
> VALUES (
> @.F_WobNum,
> @.codeuser,
> @.datedebutetat,
> @.datefinetat,
> @.datereception,
> @.datecreationdossier,
> @.numeroenregistrement,
> @.activites,
> @.produit,
> @.do,
> @.idclient,
> @.etatdossier,
> @.mediaentree,
> @.mediasortie,
> @.datefindossier,
> @.segmentclient,
> @.actions,
> @.etatexportdata,
> @.numeroenregistrementpli,
> @.taches,
> @.languecontactentrant,
> @.languecommunication,
> @.pays,
> @.datefinprevisionnelle,
> @.datelimitetraitement)
> declare @.return varchar(500)
> if @.@.error <> 0
> begin
> set @.return = 'ERROR : ' + cast(@.@.error as varchar)
> rollback tran
> end
> else
> begin
> set @.return = scope_identity()
> commit tran
> end
> select @.return
> GO
> Stored procedure 2 to GET:
> ==========================
> CREATE procedure dbo.GetIndFpsInfosById
> @.indfps_id varchar(20) = ''
> as
> begin transaction
> SELECT *
> FROM [ind_fps]
> WHERE id = @.indfps_id
> commit transaction
> GO
>

Problem on cross-tab

I want to insert Espacial field (Record number) in cross-tab report.
How is it possible?
It works nice on standered report but in cross-tab i can't do that.
eliasHello
Mr. Ello
u should write it details
so that i can----

write abt ur code|||hi siraj,

U know in standered report if u select the espacial field(Record Number)
and place it in details section then u can find the record number in the
report.

I want to do same thing in cross-tab report.

However I can't still solve ur question(2 see the total in individual page)

I did the solution which helped u to do that.(But if i place formula-3 in
report footer I can't see anything in individual page but only in last page)

If I place it in page footer then the same problem u written arises..

so help me......

ur ello|||Dear Ello
to solve my problem u can follw last help of Madhi

For ur problem i think u can use standard report & in standard report u can insert cross-tab where record count cn b used as u wish

i hv tested it :if u cn for ur problem u should inform me

bye

siraj

Monday, February 20, 2012

Problem inserting XML with DTD

Hi,
I am trying to insert a XML document into a SQL-Server 2005 column of type
XML:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE ctobject PUBLIC "-//my Ges.m.b.H.//DTD Procedural//EN"
"proced.dtd">
<ctobject>
<content>Some data with entity ref ü</content>
</ctobject>
The C#-Code for the operation is:
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "Insert XmlData(XmlData) Values(@.Col1)";
SqlParameter p1 = cmd.Parameters.Add("@.Col1", SqlDbType.Xml);
XmlTextReader reader = new XmlTextReader(fn);
reader.XmlResolver = resolver;
p2.Value = new SqlXml(reader);
cmd.ExecuteNonQuery();
The operation produces an "InvalidOperationException" - "DTD is not allowed
in XML fragments" on instantiation of the "SqlXml" type.
Removing the DOCTYPE reference eliminates the problem but of course produces
another one: "XmlException" - "Reference to undeclared entity" (caused by
the "ü" entity reference).
What can I do.
Thanks in advance,
ErwinHello Erwin,
Since DTDs are not supported by SQL Server (but XML Schemas are :-) ) you
will have to replace the ü with something else (like <uuml/>, ü or
) and then replace it again on the client side (with ü) when you fetch
it back to the client.
You should however consider not using DTDs.
HTH
/Tobias|||Hello Tobias,
thank you for the response.
Unfortunately not using DTDs is currently not an option (large set of
technical documentation from customer, who is not prepared for switching to
schemas).
So if we decide to work with SQL-Server we will need some kind of
workaround:
usage of partial schemas for indexing (performance) purposes
storage of XML with resolved entities
...
Anyway, a very important requirement is to reproduce an identical copy of
the original document on store/retrieve operations. We will therefore need
some type of replace/restore operations (the way you mentioned in your
response). As an alternative we could try to store a copy of the original
XML to a simple "varchar" column. The first solution has the divantage of
producing extra computational overhead. It also ev. manipulates the original
document structure (ev. infuencing search operations). The second solution
produces redundant data with possible problems on data modification
activities.
Kind regards,
Erwin
"Tobias Thernstrm" <ttnospam@.rbam.nospam.se> schrieb im Newsbeitrag
news:ufcBW6pbGHA.4716@.TK2MSFTNGP03.phx.gbl...
> Hello Erwin,
> Since DTDs are not supported by SQL Server (but XML Schemas are :-) ) you
> will have to replace the ü with something else (like <uuml/>, ü
> or ) and then replace it again on the client side (with ü) when you
> fetch it back to the client.
> You should however consider not using DTDs.
> HTH
> /Tobias
>

Problem inserting Rows after table creation

I am using the below SQL to insert a table. The problem is after I run this, I run another script to populate the table (see below). The population script will work if I run it as INSERT INTO ... SELECT TOP 99.9999999 PERCENT ..., but if I put 100 PERCENT, or just use no percent limiter I get the following error: Msg 8624, Internal SQL Server error.

It is weird b/c once something is inserted in the table, i can run the populate script without any problems. Any idea as to why this is happening?

Thanks,

Dave

TABLE GENERATION SCRIPT

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tbCelebroAds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tbCelebroAds]
GO

CREATE TABLE [dbo].[tbCelebroAds] (
[AdID] [int] IDENTITY (1, 1) NOT NULL ,
[BranchCode] [int] NOT NULL ,
[PropertyID] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[AdScheduleCode] [int] NOT NULL ,
[RecAtCentral] [int] NULL ,
[AdRan] [int] NOT NULL ,
[AdStatusID] [int] NOT NULL ,
[PatID] [int] NULL ,
[RunDate] [datetime] NOT NULL ,
[CreationCost] [float] NOT NULL ,
[BillCost] [float] NOT NULL ,
[AddedDate] [smalldatetime] NOT NULL
) ON [PRIMARY]

TABLE POPULATION SCRIPT

INSERT INTO tbCelebroAds (BranchCode, PropertyID, AdScheduleCode, PatID, AdStatusID, AdRan, RunDate, CreationCost, BillCost, AddedDate)
SELECT [TOP 100 PERCENT or no percent limiter doesn't work, TOP 99.9999999 PERCENT does] BranchCode, PropertyID, AdScheduleCode, cp.PatID, 6, 0, CAST(PubDate AS DATETIME), CAST(ISNULL(pat.Cost,0) AS DECIMAL(10,2)), 0, GetDate()
FROM tbCelebroView cv
LEFT JOIN tbCelebroPubs cp ON cv.PublicationName = cp.PublicationName AND cv.AdSectionName = cp.AdSectionName
LEFT JOIN tbPubToAdType pat ON cp.PatID = pat.PatID
WHERE CAST(BranchCode AS nvarchar(20)) + CAST(PropertyID AS varchar(20)) + CAST(AdScheduleCode AS nvarchar(20)) NOT IN
(SELECT CAST(BranchCode AS nvarchar(20)) + CAST(PropertyID AS varchar(20)) + CAST(AdScheduleCode AS nvarchar(20)) FROM tbCelebroAds)I wonder if it has anything to do with the fact that, in your where clause, you're excluding records that exist in the very table you're inserting into (don't know why you're doing that, but I'm sure you have your reasons). Have you tried removing that last clause to see if it will work?|||The reason I am excluding records that exist in the table is b/c I am trying to perform a sort of "Merge" where only new records get inserted.

Is there a better way of doing this?|||How about inserting existing rows into a temp table first.
Then run you main select, but where records don't exist in your temp table.

Insert into #myTemp (select cast(....) )

insert into tbCelebroAds(....)select ...
where cast(...) not in select * from #myTemp|||Thanks TJ, that is a simple solution that worked perfectly when I tried it.

Thanks again for your help!

Problem inserting Now() into a datetime field

Hi

I am trying to insert value retrieved from Now() into a datetime field in my MSDE database, but I am getting the following error, and I have no idea what is going wrong.

Arithmetic overflow error converting expression to data type datetime.
The statement has been terminated.

Here is the code I am using:

Dim user As String = MyContext.User.Identity.Name.ToString
Dim TimeDate As DateTime = Now()
Dim status As String = "Pending"

With SqlOrders.InsertParameters
.Item("UserName").DefaultValue = user
.Item("OrderDate").DefaultValue = TimeDate
.Item("Status").DefaultValue = status
End With
SqlOrders.Insert()

The date is being returned in this format23/03/2006 02:01:52, which is the same format as it should appear in the database.

could anyone please tell me where I am going wrong?
Datetimes don't have a format. Varchar/strings that represent a datetime have a format. Make sure your OrderDate parameter is set to a datetime datatype, and your problem should go away, probably.|||Thankyou, I added .Item("OrderDate").Type = TypeCode.DateTime and it works fine now :)

Problem inserting data into SQL Server 2000

Tryinna insert a new row

This is my code:
Dim myConn As SqlConnection
Dim mycmd As SqlCommand
myConn = New SqlConnection("Initial Catalog=science;" & _
"Data Source=localhost;Integrated Security=SSPI;")
mycmd = New SqlCommand("INSERT into STEP1(firstname) VALUES('Amin')", myConn)
myConn.Open()
mycmd.ExecuteNonQuery()
myConn.Close()

This is the error message I get:
The name 'firstname' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.Are you certain STEP1 is a table name? Can you run the same SQL in Query Analyzer and see what happens?|||Thank you Douglas... you made me use SQL Query Analyzer which I never used before, it's a very nice progie..

OK, I tried the following code and run it:
USE science
INSERT into STEP1(firstname) VALUES('Amin')

And the message I got:
(1 row(s) affected)

So I was amazed with the result and checked it for becoming sure. I opened Enterprise Manager, opened my table named STEP1 and... guess what? a new row with the firstname of 'Amin' and NULL for the remaining fields...

Oh my God!! plz help me... this asp.net thang is getting me old! When am I gonna learn it??|||Maybe you could try enclosing the table and column names in square brackets:


mycmd = New SqlCommand("INSERT into [STEP1]([firstname]) VALUES('Amin')", myConn)

Terri|||Thank you very much for the tip Terri

I found why this error occurs but still don't know how to solve it

I've used a function located in a self-made namespace:

Function newUser(ByVal firstname As String, ByVal surname As String, ByVal title As String,
ByVal gender As String, ByVal birthday As Integer, ByVal country As String, ByVal city As String, ByVal state As String, ByVal username11 As String, ByVal pass As String, ByVal email As String)

Dim myConn As SqlConnection
Dim mycmd As SqlCommand

myConn = New SqlConnection(ConfigurationSettings.AppSettings("MyConnection1"))

mycmd = New SqlCommand("INSERT into [users_contact]([username],[pass],[email],[firstname],[surname],[title],[gender],[birthday],[country],[city],[state]) VALUES(username,pass,email,firstname,surname,title,gender,birthday,country,city,state)", myConn)

myConn.Open()
mycmd.ExecuteNonQuery()
myConn.Close()

End Function

Maybe I have to do some kind of conversion like ToString or something
Cz when I use 'string' instead of those variables, the insert command works properly.|||You initially said your statement looked like this:

mycmd = New SqlCommand("INSERT into STEP1(firstname) VALUES('Amin')", myConn)

And now you are saying that your statement looks like this:
mycmd = New SqlCommand("INSERT into [users_contact]([username],[pass],[email],[firstname],[surname],[title],[gender],[birthday],[country],[city],[state]) VALUES(username,pass,email,firstname,surname,title,gender,birthday,country,city,state)", myConn)

This is completely different. Please be sure to supply *exact* code in the future so that you can receive accurate help.

The solution to your problem is to use SQL parameters, like this:

mycmd = New SqlCommand("INSERT into [users_contact]([username],[pass],[email],[firstname],[surname],[title],[gender],[birthday],[country],[city],[state]) VALUES(@.username,@.pass,@.email,@.firstname,@.surname,@.title,@.gender,@.birthday,@.country,@.city,@.state)", myConn)

mycmd.Parameters.Add(New SqlParameter("@.username", SqlDbType.VarChar, 99))
mycmd.Parameters("@.username").Value = username

mycmd.Parameters.Add(New SqlParameter("@.pass", SqlDbType.VarChar, 99))
mycmd.Parameters("@.pass").Value = pass

mycmd.Parameters.Add(New SqlParameter("@.email", SqlDbType.VarChar, 99))
mycmd.Parameters("@.email").Value = email

<add the rest of the parameters here
myConn.Open()
mycmd.ExecuteNonQuery()
myConn.Close()

You will need to change the SqlDbType and length as appropriate for each of the parameters.

Terri|||WwWwWoOoOoOoOoOoWwWwWwWw.......

Thank you dear Terri...

How amazing you are......

It wroked!! It was been a long time I had this prob and couldn't find any useful article.. Go on and create a website with articles. hehee

Well, I don't know how to thank you...... anyway, thanks a lot!!

visit my website: www.aminsadeghi.com|||I am glad you got it working!

There are actually a lot of articles out there on this, but I know it can be difficult to find something when you are not really sure what you are looking for.

I suggest looking through theASP.NET Quickstart Tutorials, especiallyInserting Data into a SQL Database.

Terri|||I think the ConnectionString is wrong.
try any on bellow:

myConn = New SqlConnection("Persist Security Info=False;Integrated Security=SSPI;Server=(local);Database=science;")

or

myConn = New SqlConnection("Persist Security Info=False;Integrated Security=SSPI;Server=127.0.0.1;Database=science;")

or

myConn = New SqlConnection("Server=(local);Database=science;UID=sa;PWD=;")

or

myConn = New SqlConnection("Server=127.0.0.1;Database=science;UID=sa;PWD=;")|||Dear Yijun_lee,

The connection string is totally correct, it's calling the connection string from appSettings inside the web.config file.
If you wanna learn this new method, find and see the movie on http://msdn.microsoft.com/msdntv - Application Settings - Rob Howard

and Dear Terri,

You think I didn't search for it? as a matter of fact the problem is with Microsoft that doesn't offer free learning stuff for it's new programming language.
To get the answer of this question i had, i read the link you dropped for me, i remember i read that b4, but it only describes how to add 'data' data, and it didn't show how to insert untyped variables that u mentioned to make it look like this: @.variable and after that typing some SQL Parameters for it...
To learn this I even downloaded ASP.NET Kit... and nothing useful at all.

I believe now that Microsoft has built this very nice ASP.NET language, it has to do some work to make it comprehensive and popular.

Anyway special thanks to you dear Terri, Rob Howard (as an intellectual maker of ASP.NET) and ofcourse Bill Gates ;)

Problem inserting data into database name having a '.'

hi all,
I am facing a problem while i try to insert data into a database (database
name has a '.')
The insert statement is something like this
insert into <servername>.<databasename>.dbo.<tablename> values...
ie INSERT INTO [blrkec42046d].[asdos1.1].[dbo.DLD_Customer]
I tried enclosing the servername,database name and tablename with in square
brackets([]). Still it is giving error 'Invalid object name'.
Please suggest some solution
TIA
Deepu[blrkec42046d].[asdos1.1].[dbo.DLD_Customer]
The problem here is that both the owner and the object name are enclosed in
the same brackets resulting in an invalid object reference.
Try this:
[blrkec42046d].[asdos1.1].[dbo].[DLD_Customer]
And catch up on your reading, please.
http://msdn.microsoft.com/library/d... />
3_9c8j.asp
ML|||Including a periods or spaces as part of an database object name is not only
wrong, it is exceptionally silly. Just go ahead and replace that period with
an underscore '_' and , if someone complains, tell them to change their
programming as needed.
"Deepu V" <DeepuV@.discussions.microsoft.com> wrote in message
news:36447E5C-0AE0-4208-9DAE-348BF4E5E615@.microsoft.com...
> hi all,
> I am facing a problem while i try to insert data into a database (database
> name has a '.')
> The insert statement is something like this
> insert into <servername>.<databasename>.dbo.<tablename> values...
> ie INSERT INTO [blrkec42046d].[asdos1.1].[dbo.DLD_Customer]
> I tried enclosing the servername,database name and tablename with in
> square
> brackets([]). Still it is giving error 'Invalid object name'.
> Please suggest some solution
> TIA
> Deepu
>

Problem inserting data into a SQL Express database

I am trying to implement a code behind page (in VB) to insert data into a sql express database but something is not right. Any help would be greatly appreciated. The following is the code I have:

Protected Sub SaveButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveButton.Click
Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\News.mdf;Integrated Security=True;User Instance=True;Asynchronous Processing=true"
Dim sqlInsert As String = "INSERT INTO news_Article (Heading, Story, Author, Show_on_homepage) VALUES(@.heading, @.story, @.author, @.show)"
Dim conn As New System.Data.SqlClient.SqlConnection(connString)
Dim cmd As New System.Data.SqlClient.SqlCommand(sqlInsert, conn)
Dim heading = HeadingTextBox.Text
Dim story = StoryEditor.Value
Dim author = AuthorTextBox.Text
Dim show = ShowHPCheckBox.Checked

conn.Open()
cmd.BeginExecuteNonQuery()
conn.Close()

End Sub

Instead of
Dim heading = HeadingTextBox.Text

Do
cmd.Parameters.AddWithValue("@.heading", HeadingTextBox.Text)

Happy coding!

|||Cheers for the quick reply. I tried what you suggested but it is still not going into the database. Back to the drawing board I goConfused|||

Hi Dragpop,

I agree with Mikael that you need to use

cmd.Parameters.AddWithValue("@.heading", HeadingTextBox.Text)

for each parameter. Also, when you're trying to execute it, you need to use cmd.ExecuteNonQuery(), since cmd.BeginExecuteNonQuery() is for asynchronous execution.

HTH. If this does not answer you question, please feel free to mark it as Not Answered and post your reply. Thanks!

|||

Cheers for the advise Kevin. I have it all sorted now and is working great.

Problem inserting data in SQL express

Hello everybody

I'm working with a database and trying to add data to the database with the next stameny:

INSERT INTO table VALUES ('value1')

but the result of doing this, even with the Management studio, is the value value1 with one space at the end. It is like 'value1 '

Any clue?

Thank you very much and greetings from spain.

Santiago

Hi,

Most likely your field declared as CHAR(7), not VARCHAR(7). Length of your string is 6 characters and for the CHAR types SQL Server fills rest of the string with the spaces. This is by-design. If you need a value without spaces, then you would need to use VARCHAR type for this field

|||Thank you very much for the help, problem solved.

Problem inserting calculated data using sqldatasource, PLEASE HELP....!

Hi, I have created a website and I have a web form, I need to capture data and calculate fields and then insert the calculated field including the data into a sqlserver database. I created a store procedure and the parameters for the txt boxes is working fine. But the calculated fieldds are not getting inserted. Can someone please help? the code for insert is below: For the calculated field, I used txtboxes which "hold" the calculated field in the submit button event. I also tried using query string field

like this: but that did not work either. Help will be very much appreciated.

<asp:QueryStringParameterDefaultValue="1"Name="totlabchg"QueryStringField="laborcharge"Type="Decimal"/>__________________<InsertParameters><asp:FormParameterDefaultValue="0"FormField="txtaccount"Name="ActNumber"Type="String"/><asp:FormParameterDefaultValue="0"FormField="txtmeter"Name="MeterNumber"Type="String"/><asp:FormParameterDefaultValue="0"FormField="txtdov"Name="VisitDate"Type="DateTime"/><asp:FormParameterDefaultValue=""FormField="txtsvadd"Name="SvAdd"Type="String"/><asp:ParameterName="TampId2"Type="Int32"/><asp:ParameterDefaultValue="64.44"Name="charge1"Type="Decimal"/><asp:FormParameterFormField="txtq1"Name="quantity1"Type="Int32"/><asp:QueryStringParameterDefaultValue="1"Name="subtotal1"QueryStringField="sub1"Type="Decimal"/><asp:FormParameterDefaultValue="1"FormField="txtpeople"Name="labor"Type="Int32"/><asp:FormParameterDefaultValue="1"FormField="txthrs"Name="laborhrs"Type="Decimal"/><asp:FormParameterDefaultValue="1"FormField="txttotlab"Name="totlabchg"Type="Decimal"/><asp:ParameterDefaultValue="300.00"Name="flatrate"Type="Decimal"/><asp:FormParameterDefaultValue="1"FormField="txttotalcharge"Name="totalcharge"Type="Decimal"/><asp:FormParameterDefaultValue="1"FormField="txtgrandtotal"Name="grandtotal"Type="Decimal"/><asp:ParameterDirection="ReturnValue"Name="RETURN_VALUE"Type="Int32"/></InsertParameters>

Thanks.

First, I have no idea what you're doing, so I'm working a little blind. Can you put a breakpoint in your app to see whether or not the calculated field is populated before the insert? You might have to put code into an event to see what's going on. Second, if you're using a stored procedure to do the insert, and it has the values that you're doing the calculation on, why not have it generate the calculated field? That might be easier in the short term.

problem inserting in database

i have a page writing to a dsatabase. this is the string

<code>

cmd = new sqlcommand("insert into company_locations (company_id, location_type, location_name, contact, address, suite, address2, city, state, zip, phone, extension, fax, comments) Values ('" & provider_id & "', '" & location_type.selectedvalue & "', '" & location_name.text & "', '" & contact.text & "', '" & address.text & "', '" & suite.text & "', '" & address2.text & "', '" & city.text & "', '" & states.selecteditem.value & "', '" & zip.text & "', '" & phone.text & "', '" & extension.text & "', '" & fax.text & "', '" & comments.text & "')", xDb_Conn_Str)

</code>

the problem is that in location_name, I am allowing ' as a valid character. Can anyone help me with this. everytime i execute my statement is truncated because of '.

thanks

Your suffering from a problem that is only slightly less serious than the one that you will face in production: your code is liable to SQL injection attacks, assuming that the input is coming from the user.

Consider what would happen if the entry for, say, contact.text contained:

joe' ); DROP TABLE company_locations; --

Given the right level of privilege, your company_locations table would disappear. Note that this is probably the least of your worries - hackers would start attempting to run command line code on you SQL Server via the built in stored procedure for executing shell code.

You should use parameterised queries to overcome both your problem and to help mitigate against SQL injection attacks. Thus you should be using

... Values( @.ProviderId, @.LocationType, etc. )

for the command text, and then add SqlParameter objects for each parameter

eg

cmd.Parameters.Add( "@.ProviderId", provider_id )

(Note that there are lots of overloads for creating parameters, or you can create the SqlParameter object separately and then add it to the Parameters collection).|||I had understood the problem with sql injectioons. I had already implemented validation string to ensure that certain characters would not be allowed for those exact reason. It was just the ' that I was needing to add. Thanks for the advice you gave me though, it will help. I did not realize that by passing my text as a parameter that I could include the apostrophe. Thanks for the help.|||

msamford wrote:

I had already implemented validation string to ensure thatcertain characters would not be allowed for those exact reason.


This approach (filtering out bad input) is called "blacklisting" and isnot at all recommended. "Whitelisting" (letting in only expectedinput) is much preferred. But parameters are the mostpreferredapproach of all -- you should always use parameters.

Problem Insert into from Linked Server SP.

Hi All , I am using SQL Server 2005 and trying to Insert the Data from Linked server SP but i am getting Error Like "Transaction context in use by another session." but the same is Working in SQL Server 2000.

Example Code :

create table #sSS

(

mmmm varchar(200)

)

Insert into #sSS (mmmm) Exec IC2.IC2.dbo.SSA

Msg 3910, Level 16, State 2, Line 1

Transaction context in use by another session.

Pls any one help me to solve this Issue

Regards

Sivaraman Latchapathi

Is this a loopback linked server? If so, it's a known, unsupported issue.
http://msdn2.microsoft.com/en-us/library/ms188716.aspx

The workaround is to split the insert/exec into 2 steps:
1. execute the remote stored procedure and insert the data into a #remote table
2. insert into #local select * from #remote