Showing posts with label retrieve. Show all posts
Showing posts with label retrieve. Show all posts

Wednesday, March 28, 2012

Problem Retrieving SCOPE_IDENTITY

A couple of Web applications in different SQL Server 2000 databases use SCOPE_IDENTITY to retrieve the key value of a record that was just inserted. It works--most of the time. However, from time to time the identity value is not retrieved. Evidence suggests that in these cases, a null value is being retrieved. This has forced me to come up with less-than-ideal workarounds for the missing identity value.

Does anyone have any idea why SCOPE_IDENTITY sometimes fails to retrieve the identity value and transmit it back to the Web page? Could a network issue cause the problem? Is there anything I can do other than rewrite the apps to use a different algorithm than using SCOPE_IDENTITY? Thanks.

I am not aware of any issues with SCOPE_IDENTITY(); this might be an application / connection issue and not a problem with SCOPE_IDENTITY(). I am certainly interested in the outcome of this. Can somebody please check me on this?|||

If you are using embedded SQL in your application it might be worth placing this logic into a stored procedure and calling that from your application. That should avoid any comms problems as the procedure will run or not run as a single call (and not have a problem between statements in the operation).

|||

Yes, the web app uses embedded SQL in classic ASP. The application was written in classic ASP and there has never been a good reason to rewrite it. The web app is the only application that performs DML on the table--there are no separate triggers or other ways into the table.

How could an embedded SQL statement in a single Web page cause scope problems? One Web page consulted during the research on this problem said this situation should be treated as a single scope.

I will probably try the stored procedure method. But I am curious as to why all sources practically demand that SCOPE_IDENTITY be used within a stored procedure when it is allowed to work in other situations.

Thanks for the input.

problem retrieving correct max(date) row from this dataset

Hello,
I respectfully request if someone could help me modify the following query:
The goal is to retrieve a record with a curExpireDate of 12/31/05 where ther
e
is more than one row for a given curRecordID - note: in the following
dataset there is only one correct row that I want to retrieve. So for given
curRecordID there is more than one row for a curExpireDate >= 12/31/05. The
n
if curEntryDate for a curExpireDate of 12/31/05 is greater than the
curEntryDate for curExpireDate of 12/31/06 (for the same curRecordID) then I
want to retrieve that row.
The following subdataset (the actual dataset contains thousands of rows
where I need to do the same thing) contains one row where Max(curExpireDate)
= 12/31/05. I don't want that row. There are 3 more curRecordID's with
curExpireDate of 12/31/05 and 12/31/06. For the rows with curRecordID =
18537 this ID contains a row for curExpireDate = 12/31/05 where
Max(curEntryDate) is greater than the curEntryDate for curExpireDate of
12/31/06 for ID = 18537. None of the otherID's has this condition. I need
to retrieve ID 18537 where curEntryDate = 1/27/06 and curExpireDate =
12/31/05.
Here is the dataset and the query I have been experimenting with:
create table #temp4(curRecordID int,
curEntryDate datetime, curExpireDate datetime)
insert Into #temp4
select 12783, '2005-04-07', '2005-12-31' Union
select 12783, '2004-01-12', '2005-12-31' Union
select 12783, '2006-02-03', '2006-12-31' Union
select 12783, '2005-01-11', '2006-12-31' Union
select 29714, '2005-06-29', '2005-12-31' Union
select 29714, '2005-02-02', '2006-12-31' Union
select 29714, '2005-12-01', '2006-12-31' Union
select 18537, '2004-12-10', '2005-12-31' Union
select 18537, '2006-01-27', '2005-12-31' Union --<--yes want this row
select 18537, '2006-01-10', '2006-12-31' Union
select 38537, '2004-12-10', '2005-12-31' --<--don't want this row
SELECT * FROM #temp4 as X
WHERE
curRecordID NOT IN --the list of recid from beginning
(SELECT curRecordID FROM #temp4 GROUP BY curRecordID
HAVING MAX(curExpireDate)='12/31/05')
AND
curExpireDate = '12/31/05' --order by curRecordID
AND curEntryDate >
(select top 1 curEntryDate from #temp4 as Y
where X.curRecordID = Y.curRecordID
and Y.curExpireDate =
(select max(curExpireDate) from #temp4 as Z
where X.curRecordID = Z.curRecordID))
This is the current resultset - which is not the desired resultset
curRecID curEntryDate curExpireDate
12783 2005-04-07 00:00:00.000 2005-12-31 00:00:00.000 --X
18537 2006-01-27 00:00:00.000 2005-12-31 00:00:00.000 -- +
29714 2005-06-29 00:00:00.000 2005-12-31 00:00:00.000 --X
There is no way for me to isolate my desired row from this resultset
The desired resultset is this:
curRecID curEntryDate curExpireDate
18537 2006-01-27 00:00:00.000 2005-12-31 00:00:00.000
Any help appreciated,
Thanks,
RichI think I found my problem. I changed
(select top 1 curEntryDate from #temp4 as Y...
to
(select Max(curEntryDate) from #temp4 as Y
This is now giving me the desired result in my test case. Hopefully, will
do the same for the actual data.
"Rich" wrote:

> Hello,
> I respectfully request if someone could help me modify the following query
:
> The goal is to retrieve a record with a curExpireDate of 12/31/05 where th
ere
> is more than one row for a given curRecordID - note: in the following
> dataset there is only one correct row that I want to retrieve. So for giv
en
> curRecordID there is more than one row for a curExpireDate >= 12/31/05. T
hen
> if curEntryDate for a curExpireDate of 12/31/05 is greater than the
> curEntryDate for curExpireDate of 12/31/06 (for the same curRecordID) then
I
> want to retrieve that row.
> The following subdataset (the actual dataset contains thousands of rows
> where I need to do the same thing) contains one row where Max(curExpireDat
e)
> = 12/31/05. I don't want that row. There are 3 more curRecordID's with
> curExpireDate of 12/31/05 and 12/31/06. For the rows with curRecordID =
> 18537 this ID contains a row for curExpireDate = 12/31/05 where
> Max(curEntryDate) is greater than the curEntryDate for curExpireDate of
> 12/31/06 for ID = 18537. None of the otherID's has this condition. I nee
d
> to retrieve ID 18537 where curEntryDate = 1/27/06 and curExpireDate =
> 12/31/05.
> Here is the dataset and the query I have been experimenting with:
> create table #temp4(curRecordID int,
> curEntryDate datetime, curExpireDate datetime)
> insert Into #temp4
> select 12783, '2005-04-07', '2005-12-31' Union
> select 12783, '2004-01-12', '2005-12-31' Union
> select 12783, '2006-02-03', '2006-12-31' Union
> select 12783, '2005-01-11', '2006-12-31' Union
> select 29714, '2005-06-29', '2005-12-31' Union
> select 29714, '2005-02-02', '2006-12-31' Union
> select 29714, '2005-12-01', '2006-12-31' Union
> select 18537, '2004-12-10', '2005-12-31' Union
> select 18537, '2006-01-27', '2005-12-31' Union --<--yes want this row
> select 18537, '2006-01-10', '2006-12-31' Union
> select 38537, '2004-12-10', '2005-12-31' --<--don't want this row
> SELECT * FROM #temp4 as X
> WHERE
> curRecordID NOT IN --the list of recid from beginning
> (SELECT curRecordID FROM #temp4 GROUP BY curRecordID
> HAVING MAX(curExpireDate)='12/31/05')
> AND
> curExpireDate = '12/31/05' --order by curRecordID
> AND curEntryDate >
> (select top 1 curEntryDate from #temp4 as Y
> where X.curRecordID = Y.curRecordID
> and Y.curExpireDate =
> (select max(curExpireDate) from #temp4 as Z
> where X.curRecordID = Z.curRecordID))
>
> This is the current resultset - which is not the desired resultset
> curRecID curEntryDate curExpireDa
te
> 12783 2005-04-07 00:00:00.000 2005-12-31 00:00:00.000 --X
> 18537 2006-01-27 00:00:00.000 2005-12-31 00:00:00.000 -- +
> 29714 2005-06-29 00:00:00.000 2005-12-31 00:00:00.000 --X
> There is no way for me to isolate my desired row from this resultset
> The desired resultset is this:
> curRecID curEntryDate curExpireDa
te
> 18537 2006-01-27 00:00:00.000 2005-12-31 00:00:00.000
> Any help appreciated,
> Thanks,
> Rich

Friday, March 23, 2012

Problem Reading Image Data from SQL Server using ADO.NET

Hi Community,
I think I can store Binary Data in SQL Server but when I try to retrieve it,
I always only get one byte.
I think I stored my Binary Data in SQL Server in a Colum of Type Image. At
least when I execute the following code, I get some significant network
traffic. When I check the database with query analyzer, I see 4 Hex Chars in
the image colum. Like 0xe0 etc.
This is my first Question, does this mean that only 4 Bytes ended up in the
Database and my problem starts here or is this the preview mode of the image
daty type in query analyzer like I suppose?
Store Image to SQL-Server:
float[] image = MyImageData in a One Dimensional Float Array;
int byte_size = image.length * 4;
byte[] image_buffer = new byte[byte_size];
Buffer. BlockCopy(image,0,image_buffer,0,byte_si
ze);
cmd = new SqlCommand("AddImage",Conn);
cmd.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("@.blob", SqlDbType.VarBinary, image_buffer.Length,
ParameterDirection.Input, false, 0, 0, null,
DataRowVersion.Current,image_buffer);
cmd.Parameters.Add(param);
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
As I already said, regarding the network traffic and the amount of time it
takes to execute this code, I think my image data is in sql server now.
When I try to retrieve it, I always only get one byte per Image.
Retreive Image-Data:
Conn.Open();
int chunkSize = 255;
using(reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
long bytesize = reader.GetBytes(5, 0, null, 0, 0);
byte[] imageData = new byte[bytesize]; //This always returns 1
long bytesread = 0;
int curpos = 0;
while (bytesread < bytesize)
{
bytesread += reader.GetBytes(5, curpos, imageData, curpos, chunkSize);
curpos += chunkSize;
}
Buffer.BlockCopy(imageData,0,result.data,curpos*byteoffset,byteoffset);
}
}
The Code above is from ado documentation. It says that after this loop, the
bytes from the imagedata colum are in the imagedata array. In my case I
always only get one byte.
I don′t have significant network traffic reading from sql-server there is
realy only one byte transfered.
Can somebody please tell me, what I am doing wrong and how I can check if
the data i want to retreive is realy in the database.
Can you see the full content of a image field in query analyzer?
What happened to the rest of my data, I don′t get an index out of bound
exception when I fill in 65000 Bytes but there seems to be only one byte
there afterwards.
Thanks in advance for your efforts
Best Regards
Chucker"Chucker" <Chucker@.discussions.microsoft.com> wrote in message
news:CC4F035E-EF80-4775-94CE-8F45FDC2DF2F@.microsoft.com...
> Hi Community,
> I think I can store Binary Data in SQL Server but when I try to retrieve
> it,
> I always only get one byte.
> I think I stored my Binary Data in SQL Server in a Colum of Type Image. At
> least when I execute the following code, I get some significant network
> traffic. When I check the database with query analyzer, I see 4 Hex Chars
> in
> the image colum. Like 0xe0 etc.
> This is my first Question, does this mean that only 4 Bytes ended up in
> the
> Database and my problem starts here or is this the preview mode of the
> image
> daty type in query analyzer like I suppose?
>
I can't see anything particularly wrong with the code you posted.
Here's a complete working example (.net 2.0);
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Diagnostics;
public class Program
{
static void Main(string[] args)
{
System.Diagnostics.Debug.Listeners.Add(new
TextWriterTraceListener(Console.Out));
try
{
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.IntegratedSecurity = true;
cb.DataSource = "(local)";
using (SqlConnection con = new SqlConnection(cb.ConnectionString))
{
con.Open();
new SqlCommand("create table #blobtest(id int identity primary key,
blob image)",con).ExecuteNonQuery();
float[] image = new float[5000];
image[image.Length -1] = 4f;
int byte_size = image.Length * sizeof(float);
byte[] image_buffer = new byte[byte_size];
Buffer. BlockCopy(image,0,image_buffer,0,byte_si
ze);
SqlCommand cmdInsert = new SqlCommand("insert into #blobtest(blob)
values (@.blob)", con);
SqlParameter param = cmdInsert.Parameters.Add(new
SqlParameter("@.blob",
SqlDbType.Image,
image_buffer.Length));
param.Value = image_buffer;
cmdInsert.ExecuteNonQuery();
//now read
int chunkSize = 255;
SqlCommand cmdRead = new SqlCommand("select id, datalength(blob)
bytes, blob from #blobtest", con);
using (SqlDataReader reader =
cmdRead.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
int actualBytes = reader.GetInt32(1);
long bytesize = reader.GetBytes(2, 0, null, 0, 0);
Console.WriteLine("Actual Bytes: {0}, GetBytes reported {1}",
actualBytes, bytesize);
byte[] buf = new byte[chunkSize * sizeof(float)];
float[] nums = new float[bytesize/sizeof(float)];
int bytesread = 0;
while (bytesread < bytesize)
{
int bytes = (int)reader.GetBytes(2, bytesread, buf, 0,
buf.Length);
Buffer.BlockCopy(buf, 0, nums, bytesread, bytes);
bytesread += bytes;
}
Console.WriteLine("nums length {0}, first {1}, last {2}",
nums.Length, nums[0], nums[nums.Length - 1]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Hit any key to exit.");
Console.ReadKey();
}
}
David|||Thanks David, you are right, i made a very stupid mistake, I wrote binary
instead of varbinary in one place thanks for your help
Chucker
"David Browne" wrote:

> "Chucker" <Chucker@.discussions.microsoft.com> wrote in message
> news:CC4F035E-EF80-4775-94CE-8F45FDC2DF2F@.microsoft.com...
> I can't see anything particularly wrong with the code you posted.
> Here's a complete working example (.net 2.0);
> using System;
> using System.Data;
> using System.Data.SqlClient;
> using System.Collections.Generic;
> using System.Diagnostics;
> public class Program
> {
> static void Main(string[] args)
> {
> System.Diagnostics.Debug.Listeners.Add(new
> TextWriterTraceListener(Console.Out));
> try
> {
> SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
> cb.IntegratedSecurity = true;
> cb.DataSource = "(local)";
> using (SqlConnection con = new SqlConnection(cb.ConnectionString))
> {
> con.Open();
> new SqlCommand("create table #blobtest(id int identity primary key
,
> blob image)",con).ExecuteNonQuery();
>
> float[] image = new float[5000];
> image[image.Length -1] = 4f;
> int byte_size = image.Length * sizeof(float);
> byte[] image_buffer = new byte[byte_size];
> Buffer. BlockCopy(image,0,image_buffer,0,byte_si
ze);
> SqlCommand cmdInsert = new SqlCommand("insert into #blobtest(blob)
> values (@.blob)", con);
> SqlParameter param = cmdInsert.Parameters.Add(new
> SqlParameter("@.blob",
> SqlDbType.Image,
> image_buffer.Length));
> param.Value = image_buffer;
> cmdInsert.ExecuteNonQuery();
>
> //now read
> int chunkSize = 255;
> SqlCommand cmdRead = new SqlCommand("select id, datalength(blob)
> bytes, blob from #blobtest", con);
> using (SqlDataReader reader =
> cmdRead.ExecuteReader(CommandBehavior.SequentialAccess))
> {
> while (reader.Read())
> {
> int actualBytes = reader.GetInt32(1);
> long bytesize = reader.GetBytes(2, 0, null, 0, 0);
> Console.WriteLine("Actual Bytes: {0}, GetBytes reported {1}",
> actualBytes, bytesize);
> byte[] buf = new byte[chunkSize * sizeof(float)];
> float[] nums = new float[bytesize/sizeof(float)];
> int bytesread = 0;
> while (bytesread < bytesize)
> {
> int bytes = (int)reader.GetBytes(2, bytesread, buf, 0,
> buf.Length);
> Buffer.BlockCopy(buf, 0, nums, bytesread, bytes);
> bytesread += bytes;
> }
> Console.WriteLine("nums length {0}, first {1}, last {2}",
> nums.Length, nums[0], nums[nums.Length - 1]);
> }
> }
> }
> }
> catch (Exception ex)
> {
> Console.WriteLine(ex);
> }
> Console.WriteLine("Hit any key to exit.");
> Console.ReadKey();
> }
> }
>
>
>
>
> David
>
>

Monday, March 12, 2012

Problem of max(count(*))

Can someone tell me why the following sql statement cannot retrieve the
maximum count of the record:

SELECT col, max(count(*)) FROM table
GROUP BY col

And also, can I use one sql statement to retrieve the maximum count of the
record? If not, how?

Thank you more!!Hello,

you use two group function MAX and COUNT in one statement, but there is only on group by function. So the error will be "no group ..."

The count is already the maximum in the group col, but if you need the
maximum of all col the use

SELECT max(count(*)) FROM table

Hope that helps

Manfred Peter
Alligator Company Software GmbH
http://www.alligatorsql.com|||i dont know what you exactly want to retrive using max(count(*))

actually count(*) will return only one value which is maximum.

so i think the following should work for u

SELECT col, count(*) FROM table
GROUP BY col|||hi,

the only way max(count()) will have any meaning, is by getting more then 1 row from count()....
Only that case the max function will have any relevance.

example:
select count(*) from emp return one row. This is always the max
select count(*), deptno from emp group by deptno will return 3 rows. Now I have a situation in which a max would have relevance.

Hope this helps|||SELECT max(count(*)) FROM table
GROUP BY col
/*that's all folks!*/

Friday, March 9, 2012

problem maybe with IN

Hi all,

I've a SP that retrieve a list of users. The problem is that on this SP i want return a list of all users or only based on a specific filter gived by the customer.

I don't want ot use IF statements to see if for example the variables @.username contains something or is null.

Ok, so.. there is a method that return all the users if the variables is null and a specific user is the variable contain something without use condition?

Please note also that is not only one variable but can be more (ie, filter by password and email too)

Thanks for the help!

Crisif you dynamically build your query
and then execute it

will that do ?|||The query can be

select ...
from ...
where (field1 = @.param1 or @.param1 is null)
and (field2 = @.param2 or @.param2 is null)

Originally posted by bortolo
Hi all,

I've a SP that retrieve a list of users. The problem is that on this SP i want return a list of all users or only based on a specific filter gived by the customer.

I don't want ot use IF statements to see if for example the variables @.username contains something or is null.

Ok, so.. there is a method that return all the users if the variables is null and a specific user is the variable contain something without use condition?

Please note also that is not only one variable but can be more (ie, filter by password and email too)

Thanks for the help!

Cris|||select ...
from ...
where (field1 = @.param1 or @.param1 is null)
and (field2 = @.param2 or @.param2 is null)

nice solution !|||create proc sp_return_users (
@.uid char(10) = null,
@.pwd varchar(16) = null,
@.eml varchar(128) = null)
as
declare @.tbl table (
uid char(10) null, @.pwd varchar(16) null, @.eml varchar(128) null)

insert @.tbl values (isnull(@.uid, '%'), isnull(@.pwd, '%'), isull(@.eml, '%'))

select u.* from dbo.tblusers u
inner join @.tbl t
on (u.uid like t.uid
and u.pwd like t.pwd
and u.eml like t.eml)
go