Showing posts with label int. Show all posts
Showing posts with label int. Show all posts

Sunday, March 11, 2012

Double Table Insert

Tables :

EmailUsers
ID int - PK
Email nvarchar(256)

ListsUsers
ListID int - FK to List Table - Combo PK
UserID int - FK to EmailUsers Table - Combo PK

When a person adds a user I need to:
A. insert them as a new entry into EmailUsers - no problem
B. insert their EmailUsers.ID from step A and ListID (passed in parameter) into ListsUsers - not so easy
C. if they're already in EmailUsers don't insert them but pass their existing EmailUsers.ID to part B

Any thoughts or examples I can follow? Maybe it's easier to do two seperate queries and control the if exists logic in asp.net?I would check out the starter kits--such as the TimeTracker. They illustrate the following:

if select Count(*) from emailusers where .. = 0
Begin
Begin Transaction

insert into Email users

select @.id = @.@.identity

if no error
continue

insert into ListUsers
(x, @.id)

Commit Trans
end
else
select @.id = id from emailusers

insert into ListUsers
(x, @.id)

Hope this points you in the right direction|||


CREATE PROCEDURE SaveUser
@.EmailAddress VARCHAR(256),
@.ListID INT
AS
DECLARE @.UserID INT

SELECT @.UserID = ID FROM EmailUsers WHERE Email = @.EmailAddress

IF @.UserID IS NULL
BEGIN
INSERT INTO EmailUsers (Email) VALUES (@.EmailAddress)
SET @.UserID = @.@.IDENTITY
END

INSERT INTO ListUsers (ListID, UserID) VALUES (@.ListID, @.UserID)

|||I'd say use SCOPE_IDENTITY() rather than @.@.IDENTITY.. if there was another insert at the same time @.@.IDENTITY will return the id of that insert. SCOPE_IDENTITY() will work within the scope of the insert..

hth|||ndinakar: Thanks for that little tidbit, I didn't realize there was a potential for scope issues with @.@.IDENTITY.|||it should be ok to use @.@.IDENTITY as there could be 1/1000 ( or more or less...just a guesstimate) chance of your insert coinciding with another one but that could very well runi your day...so...check out BOL for more info on them...

hth|||I was in Vegas for the past week. Will give the suggestions here a try on Monday morning.

Thanks!|||Works great but I'm slightly confused on my return value


CREATE PROCEDURE [dbo].[Add_List_Users]
@.EmailAddress nvarchar(256),
@.ListID INT
AS
DECLARE @.UserID INT
DECLARE @.returnCode INT
SELECT @.UserID = ID FROM Email_Users WHERE Email = @.EmailAddress
SET @.returnCode = 0
IF @.UserID IS NULL
BEGIN
INSERT INTO Email_Users (Email) VALUES (@.EmailAddress)
SET @.UserID = @.@.IDENTITY
SET @.returnCode = @.returnCode + 1
END
if not exists (select * from Lists_Users where ListID = @.ListID and UserID = @.UserID)
INSERT INTO Lists_Users (ListID, UserID) VALUES (@.ListID, @.UserID)
SET @.returnCode = @.returnCode + 2
return @.returnCode
GO

Scenarios:
User Added to Users Table and List Table - returnCode 3
User exists in Users Table and Added to List Table - return code 2
User exists in both tables - return code 0

Actual Return Values:
2
1
-1

That's fine, I just check for 2, 1, -1 instead of 3, 2, 0 but I'd like to know why the values returned aren't logically what they should be?

SET @.returnCode = 0
SET @.returnCode = @.returnCode + 1
SET @.returnCode = @.returnCode + 2
shouldn't that = 3??

It's as if @.returnCode starts off at -1 since all the return values are 1 less than I expect them to be.|||The SCOPE_IDENTITY really comes into play if you've got hidden inserts. For example, another insert triggered from your original insert. That's where simply returning @.@.IDENTIY becomes totally wrong. Like the poster said, use SCOPE_IDENTITY and you can sleep at night!|||plus..you might want to look at OUTPUT Parameters to return the id ..check out BOL for more info on OUTPUT parameters..

hth

Wednesday, March 7, 2012

Dont understand GROUP BY...

I have a table Test_GUID, with fields id as int PK IDENTITY, GUID as varchar(50), and Version as tinyint. I put data in it such as

id GUID Version
------
1 abc 1
2 abc 2
3 def 1

Then I tried to get the following result:

id GUID Version
------
1 abc 2
3 def 1

By using a query:

SELECT GUID, MAX(Version) AS MaxVersion, id
FROM dbo.Test_GUID
GROUP BY GUID

But then I get an error because id is not being aggregated.

This works

SELECT GUID, MAX(Version) AS MaxVersion
FROM dbo.Test_GUID
GROUP BY GUID

but then how do I get the id of each record?use a correlated subquery, it's the same as grouping
select id
, GUID
, Version as MaxVersion
from dbo.Test_GUID as foo
where Version
= ( select max(Version)
from dbo.Test_GUID
where GUID
= foo.GUID )|||Thanks, was able to incorporate this into other queries, works great!

Don't Know How To Explain It

The tables are as follows
CREATE TABLE dbo.Blogs
dId int * PRIMARY
posted datetime(8)
title nvarchar(50)
catgy nvarchar(50)
blogs nvarchar(500)
picId int
UName nvarchar(50)
CREATE TABLE dbo.BlogPix
bgId int * PRIMARY
picId int
Photo nvarchar(50)
Caption(50)
UName nvarchar(50)
I dont know how to explain it but this is the way i have the application
working. The UName on every table in the system is the User name of the User
and it returns rows filtered by UName = @.Uname. However this works fin on my
application but it gets tricky when i try to filter by picId. Ok, the picId
is not a autonumber and any user can get the same number at some time
because i am using the random class to generate a number from the smallest
INT32 to the biggest so i have big scope.
its so hard to explain what i mean so i will give an example,
SELECT TOP (30) *
FROM Blogs INNER JOIN
BlogPix ON Blogs.picId = BlogPix.picId
WHERE UName = @.UName AND PicId = @.PicId
basically i want to retrieve data by using the keyfields dId or picId which
ever way i can so i can return results like the following;
bgId !!!!!!! picId !!!!!!! Photo !!!!!!! Caption !!!!!!! UName
--1--99995688--~/pix/plig.jpg--im a minger--Sean--
--2--99995688--~/pix/pliglet.jpg--im a minger--Sean--
--3--99995688--~/pix/pligkil.jpg--im a minger--Sean--
--4--99995688--~/pix/plipim.jpg--im a minger--Sean--
--5--99995688--~/pix/plim.jpg--im a minger--Sean--
dId !!!!!!! picId !!!!!!! Title !!!!!!!!!!!!!!!!!! Blogs
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Posted
!!!!!!!!!!! Catgy !!!!!!! UName
--1--99995688--Me On A Gud Day--Im going gud and life is great--21
Aug 2005--Music--Sean--
--2--2568777--Me On A Bad Day--Im going gud and life is great--21
Aug 2005--Music--Sean--
--3--12369875--Me On A Nasty Day--Im going gud and life is
great--21 Aug 2005--Music--Sean--
--4--56888999--Me On A Lovely Day--Im going gud and life is
great--21 Aug 2005--Music--Sean--
--5--5896633--Me On A Dark Day--Im going gud and life is great--21
Aug 2005--Music--Sean--
Hope this helps, i cant really explain what it is but i do knowI think you'll find your answers in the following article:
http://www.sommarskog.se/dyn-search.html
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
--
"Eamon Straughn" <blackmanvandam@.aol.com> wrote in message
news:uUu9KJCrFHA.2076@.TK2MSFTNGP14.phx.gbl...
> The tables are as follows
> CREATE TABLE dbo.Blogs
> dId int * PRIMARY
> posted datetime(8)
> title nvarchar(50)
> catgy nvarchar(50)
> blogs nvarchar(500)
> picId int
> UName nvarchar(50)
> CREATE TABLE dbo.BlogPix
> bgId int * PRIMARY
> picId int
> Photo nvarchar(50)
> Caption(50)
> UName nvarchar(50)
> I dont know how to explain it but this is the way i have the application
> working. The UName on every table in the system is the User name of the
User
> and it returns rows filtered by UName = @.Uname. However this works fin on
my
> application but it gets tricky when i try to filter by picId. Ok, the
picId
> is not a autonumber and any user can get the same number at some time
> because i am using the random class to generate a number from the smallest
> INT32 to the biggest so i have big scope.
> its so hard to explain what i mean so i will give an example,
> SELECT TOP (30) *
> FROM Blogs INNER JOIN
> BlogPix ON Blogs.picId = BlogPix.picId
> WHERE UName = @.UName AND PicId = @.PicId
> basically i want to retrieve data by using the keyfields dId or picId
which
> ever way i can so i can return results like the following;
> bgId !!!!!!! picId !!!!!!! Photo !!!!!!! Caption !!!!!!! UName
> --1--99995688--~/pix/plig.jpg--im a minger--Sean--
> --2--99995688--~/pix/pliglet.jpg--im a minger--Sean--
> --3--99995688--~/pix/pligkil.jpg--im a minger--Sean--
> --4--99995688--~/pix/plipim.jpg--im a minger--Sean--
> --5--99995688--~/pix/plim.jpg--im a minger--Sean--
> dId !!!!!!! picId !!!!!!! Title !!!!!!!!!!!!!!!!!! Blogs
> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Posted
!!!!!!!!!!! Catgy !!!!!!! UName
> --1--99995688--Me On A Gud Day--Im going gud and life is
great--21
> Aug 2005--Music--Sean--
> --2--2568777--Me On A Bad Day--Im going gud and life is great--21
> Aug 2005--Music--Sean--
> --3--12369875--Me On A Nasty Day--Im going gud and life is
> great--21 Aug 2005--Music--Sean--
> --4--56888999--Me On A Lovely Day--Im going gud and life is
> great--21 Aug 2005--Music--Sean--
> --5--5896633--Me On A Dark Day--Im going gud and life is
great--21
> Aug 2005--Music--Sean--
> Hope this helps, i cant really explain what it is but i do know
>

Sunday, February 19, 2012

Doing the lookup on the server while inserting

I have these 2 tables:
CREATE TABLE tbl_ft_testsegments (
SegmentID int(10) AUTO_INCREMENT NOT NULL,
TestID smallint(6) NOT NULL DEFAULT '0',
CarrierFreq smallint(6) NOT NULL DEFAULT '0',
BeatFreq smallint(6) NOT NULL DEFAULT '0',
BeatFreqDelta smallint(6) NOT NULL DEFAULT '0',
Duration tinyint(4) NOT NULL DEFAULT '0',
AmplitudeRampID tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY(SegmentID)
)
CREATE TABLE tbl_ft_amplituderamps (
AmplitudeRampID tinyint(4) AUTO_INCREMENT NOT NULL,
Name char(12) NOT NULL,
PRIMARY KEY(AmplitudeRampID)
)
tbl_ft_amplituderamps is constant and will not change.
On the client, I load a text file that has string values that match what is
in amplituderamps, or atleast they are supposed to!
I store this data in a business object that has the string representation of
an "amplitude ramp"
When I insert them, I am currently getting the AmplitudeRampID from
tbl_ft_amplituderamps where <text file value> = tbl_ft_amplituderamps.Name
THis isn't *too* bad cause I have a local copy of the whole table in memory.
I am considering instead of doing the insert with string instead of the ID
and doing the lookup on teh server side.
Something like:
@.myString varchar(20)
INSERT INTO tbl_ft_testsegments (AmplitudeRampID)
SELECT tbl_ft_amplituderamps.AmplitudeRampID
FROM tbl_ft_amplituderamps WHERE tbl_ft_amplituderamps.Name = myString
Being far from a professional, I'm wondering if this is the *preferred*
method? Is it better to do a little lookup on the client or should I do
this on the server?
Any suggestions would be much appreciated. I have MANY cases where I need
to do this and I would like to get teh best method sorted out before I add
the sprocs for all of the different tables.
Thanks for reading!
Steve"sklett" <sklett@.mddirect.com> wrote in message
news:uddCEzXZGHA.1204@.TK2MSFTNGP04.phx.gbl...
>I have these 2 tables:
> CREATE TABLE tbl_ft_testsegments (
> SegmentID int(10) AUTO_INCREMENT NOT NULL,
> TestID smallint(6) NOT NULL DEFAULT '0',
> CarrierFreq smallint(6) NOT NULL DEFAULT '0',
> BeatFreq smallint(6) NOT NULL DEFAULT '0',
> BeatFreqDelta smallint(6) NOT NULL DEFAULT '0',
> Duration tinyint(4) NOT NULL DEFAULT '0',
> AmplitudeRampID tinyint(4) NOT NULL DEFAULT '0',
> PRIMARY KEY(SegmentID)
> )
> CREATE TABLE tbl_ft_amplituderamps (
> AmplitudeRampID tinyint(4) AUTO_INCREMENT NOT NULL,
> Name char(12) NOT NULL,
> PRIMARY KEY(AmplitudeRampID)
> )
>
> tbl_ft_amplituderamps is constant and will not change.
> On the client, I load a text file that has string values that match what
> is in amplituderamps, or atleast they are supposed to!
> I store this data in a business object that has the string representation
> of an "amplitude ramp"
> When I insert them, I am currently getting the AmplitudeRampID from
> tbl_ft_amplituderamps where <text file value> =
> tbl_ft_amplituderamps.Name
> THis isn't *too* bad cause I have a local copy of the whole table in
> memory. I am considering instead of doing the insert with string instead
> of the ID and doing the lookup on teh server side.
> Something like:
> @.myString varchar(20)
> INSERT INTO tbl_ft_testsegments (AmplitudeRampID)
> SELECT tbl_ft_amplituderamps.AmplitudeRampID
> FROM tbl_ft_amplituderamps WHERE tbl_ft_amplituderamps.Name = myString
>
> Being far from a professional, I'm wondering if this is the *preferred*
> method? Is it better to do a little lookup on the client or should I do
> this on the server?
> Any suggestions would be much appreciated. I have MANY cases where I need
> to do this and I would like to get teh best method sorted out before I add
> the sprocs for all of the different tables.
> Thanks for reading!
> Steve
>
One approach that works well with large data sets is to insert the entire
file into a temporary "staging" table in the database, then do the whole
thing with a join:
INSERT INTO tbl_ft_testsegments (AmplitudeRampID)
SELECT DISTINCT A.AmplitudeRampID
FROM tbl_ft_amplituderamps AS A
JOIN staging AS S
ON A.Name = S.String ;
For loading the file itself you have a number of options. DTS (SQL Server
2000) or Integration Services (2005) or BCP for example.
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
--|||Hi,

> Being far from a professional, I'm wondering if this is the *preferred*
> method? Is it better to do a little lookup on the client or should I do
> this on the server?
Yes. Centralise as much of your logic on the server as possible. Keep
your client-side software as light-weight as you can - ideally, limit it to
presentation only. The processing work belongs on the server(s). Golden
rule, end of story :)
Robert.
"sklett" <sklett@.mddirect.com> wrote in message
news:uddCEzXZGHA.1204@.TK2MSFTNGP04.phx.gbl...
>I have these 2 tables:
> CREATE TABLE tbl_ft_testsegments (
> SegmentID int(10) AUTO_INCREMENT NOT NULL,
> TestID smallint(6) NOT NULL DEFAULT '0',
> CarrierFreq smallint(6) NOT NULL DEFAULT '0',
> BeatFreq smallint(6) NOT NULL DEFAULT '0',
> BeatFreqDelta smallint(6) NOT NULL DEFAULT '0',
> Duration tinyint(4) NOT NULL DEFAULT '0',
> AmplitudeRampID tinyint(4) NOT NULL DEFAULT '0',
> PRIMARY KEY(SegmentID)
> )
> CREATE TABLE tbl_ft_amplituderamps (
> AmplitudeRampID tinyint(4) AUTO_INCREMENT NOT NULL,
> Name char(12) NOT NULL,
> PRIMARY KEY(AmplitudeRampID)
> )
>
> tbl_ft_amplituderamps is constant and will not change.
> On the client, I load a text file that has string values that match what
> is in amplituderamps, or atleast they are supposed to!
> I store this data in a business object that has the string representation
> of an "amplitude ramp"
> When I insert them, I am currently getting the AmplitudeRampID from
> tbl_ft_amplituderamps where <text file value> =
> tbl_ft_amplituderamps.Name
> THis isn't *too* bad cause I have a local copy of the whole table in
> memory. I am considering instead of doing the insert with string instead
> of the ID and doing the lookup on teh server side.
> Something like:
> @.myString varchar(20)
> INSERT INTO tbl_ft_testsegments (AmplitudeRampID)
> SELECT tbl_ft_amplituderamps.AmplitudeRampID
> FROM tbl_ft_amplituderamps WHERE tbl_ft_amplituderamps.Name = myString
>
> Being far from a professional, I'm wondering if this is the *preferred*
> method? Is it better to do a little lookup on the client or should I do
> this on the server?
> Any suggestions would be much appreciated. I have MANY cases where I need
> to do this and I would like to get teh best method sorted out before I add
> the sprocs for all of the different tables.
> Thanks for reading!
> Steve
>