Showing posts with label field. Show all posts
Showing posts with label field. Show all posts

Friday, March 30, 2012

Id getting generated differently

Hi,

I created a PDA application with a database, which has a table with a uniqueidentifier field and primarykey.

While doing the bulk insert from dataset into sql mobile database, It is inserting the record but it is not inserting the id which was entered into the sql server 2005 database, instead the id by creating a new id and the code is as below.

conAdap = new SqlCeDataAdapter(strQuery, conSqlceConnection);

SqlCeCommandBuilder cmdBuilder = new SqlCeCommandBuilder(conAdap);

conAdap.Fill(dsData);

int r =conAdap.Update(dsData);

Please help me.

Thank you,

Prashant

Hi Prashant - I'm not sure I understand your issue. Could you explain in more detail and also give me somee information about the schema of the table itself? I'm interested in the list of columns, their types, PK, FKs, Indexes, and default values you have assigned on columns.

I'm also interested to know if the table is the product of an RDA pull with tracking on or merge replication article.

thanks,

Darren

ID Field Reset

This morning I made a change to two tables in my live system. All I did was add a new column in each called 'suspense' with a data type of bit and a default value of '0'.

When the users started using the system they noticed that the record ID numbers had reset and were starting from 1 and going up 2, 3, 4 etc. The last good id number was about 20500. The id columns are set as primary key with identity and increment of 1.

This shouldn't happen should it? Is it a bug? I never touched the ID column, just added the new one.I bet you made the change using Enterprise Mangler. EM tends to make these changes not with a simple alter table add column, but with a drop and re-create of the table. You can try running DBCC CHECKIDENT(table) on the table, which should reset the identity column nicely.|||That's interesting. I am going to test that on my test system now to see what happens.

Thanks!

Friday, March 23, 2012

I want to select the SECOND newest record in a table,....is this possible?

Hi!
I want to do a query against a SQL DB and by sorting a datetime field, I want to get the second newest record in the table, not the newest.
Can I do that?
/Johan Ch

You could do it like this:
SELECT TOP 1
*
FROM
(SELECT TOP 2 * FROM myTable Order by myDateTime DESC) AS A
ORDER BY
myDateTime ASC

I want to give a user access to only one field in one table

I was trying to give permissions to a user for one field in one table only.
How can I do this?
It seems that I have to give permissions to the whole database.
I have SQL 2000 using Enterprise managerGRANT SELECT (<ColumnName> ) ON <TableName> TO <User>
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"AlanM" <nooneatall@.nowhere.com> wrote in message
news:ObRkcHf1EHA.1204@.TK2MSFTNGP10.phx.gbl...
>I was trying to give permissions to a user for one field in one table only.
> How can I do this?
> It seems that I have to give permissions to the whole database.
> I have SQL 2000 using Enterprise manager
>|||To add to Roji's response, you might also consider creating a view that
returns only the data the user should see and grant SELECT permissions on
only that view to the user/role. This allows vertical and horizontal
partitioning based on your requirements. See 'Using Views as Security
Mechanisms' <adminsql.chm::/ad_security_5whf.htm> in the Books Online for
more information.
CREATE VIEW MyView
AS
SELECT MyColumn
FROM MyTable
GO
GRANT SELECT ON MyView TO MyRole
GO
Hope this helps.
Dan Guzman
SQL Server MVP
"AlanM" <nooneatall@.nowhere.com> wrote in message
news:ObRkcHf1EHA.1204@.TK2MSFTNGP10.phx.gbl...
>I was trying to give permissions to a user for one field in one table only.
> How can I do this?
> It seems that I have to give permissions to the whole database.
> I have SQL 2000 using Enterprise manager
>

Monday, March 19, 2012

i want a certain field to be sequentially increased

Hi,
I want to setup one of the fields in a table so it increments
sequentially(int data type). i.e the first record should be record 1
and the second one should be 2 and so on. This field will also be the
key field. I am new to SQL and don't know how to do this.
I am using SQL server 2000.
Thanks for the help in advance.

-S>> I want to setup one of the fields [sic] in a table so it increments
sequentially(INTEGER data type). i.e the first record [sic] should be
record 1 [sic] and the second one should be 2 and so on. This field
[sic]will also be the key field [sic]. I am new to SQL and don't know
how to do this. <<

Very new. Rows are not records; columns are not fields; keys are not
physical record numbers. You missed the most basic concept of the
RDBMS model. A key is a subset of the attributes (columns) which are
unique and not null for each entity (row) in the table. It is never a
"magic number for everything" generated by the computer which has no
meaning in the reality you are trying to model.

You actually have to think and work hard to design a database. Get a
book on data modeling and read it.|||Take a look at IDENTITY (Property) in "SQL Server Books Online".

"Sumanth Suri" <sumant_suri@.hotmail.com> wrote in message
news:a3007893.0311071034.54617b6b@.posting.google.c om...
> Hi,
> I want to setup one of the fields in a table so it increments
> sequentially(int data type). i.e the first record should be record 1
> and the second one should be 2 and so on. This field will also be the
> key field. I am new to SQL and don't know how to do this.
> I am using SQL server 2000.
> Thanks for the help in advance.
> -S|||thanks for the 40. I hear SQL FOR SMARTIES is pretty good. Any thoughts??

joe.celko@.northface.edu (--CELKO--) wrote in message news:<a264e7ea.0311071358.4db9e6b8@.posting.google.com>...
> >> I want to setup one of the fields [sic] in a table so it increments
> sequentially(INTEGER data type). i.e the first record [sic] should be
> record 1 [sic] and the second one should be 2 and so on. This field
> [sic]will also be the key field [sic]. I am new to SQL and don't know
> how to do this. <<
> Very new. Rows are not records; columns are not fields; keys are not
> physical record numbers. You missed the most basic concept of the
> RDBMS model. A key is a subset of the attributes (columns) which are
> unique and not null for each entity (row) in the table. It is never a
> "magic number for everything" generated by the computer which has no
> meaning in the reality you are trying to model.
> You actually have to think and work hard to design a database. Get a
> book on data modeling and read it.|||>> thanks for the 40. I hear SQL FOR SMARTIES is pretty good. Any
thoughts?? <<

I like it a lot -- especially when the royalty check arrives :)

--CELKO--
===========================
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Dont listen to Celko - his is too pr0 :p

go with the identity - but beware some of its behaviour, and protect
it carefully, it is not terribly robust and can totally shaft your
data relationships if you use it and let it get damaged.

"Shervin Shapourian" <ShShapourian@.hotmail.com> wrote in message news:<vqofb5e8rl3k97@.corp.supernews.com>...
> Take a look at IDENTITY (Property) in "SQL Server Books Online".
> "Sumanth Suri" <sumant_suri@.hotmail.com> wrote in message
> news:a3007893.0311071034.54617b6b@.posting.google.c om...
> > Hi,
> > I want to setup one of the fields in a table so it increments
> > sequentially(int data type). i.e the first record should be record 1
> > and the second one should be 2 and so on. This field will also be the
> > key field. I am new to SQL and don't know how to do this.
> > I am using SQL server 2000.
> > Thanks for the help in advance.
> > -S|||Wang,

I do agree with you. These are all features that help programmers to develop
more efficient applications. It all depends on how good you are, if you are
a terrible programmer then it doesn't matter whether you use IDENTITY or
not, you will end up with a piece of crap anyway. A professionals is someone
who can take advantage of these features and use them wisely to help
developing their creative ideas without making a mess.

Shervin

"WangKhar" <Wangkhar@.yahoo.com> wrote in message
news:bb269444.0311110220.539cf94d@.posting.google.c om...
> Dont listen to Celko - his is too pr0 :p
> go with the identity - but beware some of its behaviour, and protect
> it carefully, it is not terribly robust and can totally shaft your
> data relationships if you use it and let it get damaged.
>
>
> "Shervin Shapourian" <ShShapourian@.hotmail.com> wrote in message
news:<vqofb5e8rl3k97@.corp.supernews.com>...
> > Take a look at IDENTITY (Property) in "SQL Server Books Online".
> > "Sumanth Suri" <sumant_suri@.hotmail.com> wrote in message
> > news:a3007893.0311071034.54617b6b@.posting.google.c om...
> > > Hi,
> > > I want to setup one of the fields in a table so it increments
> > > sequentially(int data type). i.e the first record should be record 1
> > > and the second one should be 2 and so on. This field will also be the
> > > key field. I am new to SQL and don't know how to do this.
> > > I am using SQL server 2000.
> > > Thanks for the help in advance.
> > > > -S|||how would you protect the behavior of IDENTITY?
Shervin and wangkhar thanks for the help.
Celko, Don't expect any royalty from this beginner!!

Wangkhar@.yahoo.com (WangKhar) wrote in message news:<bb269444.0311110220.539cf94d@.posting.google.com>...
> Dont listen to Celko - his is too pr0 :p
> go with the identity - but beware some of its behaviour, and protect
> it carefully, it is not terribly robust and can totally shaft your
> data relationships if you use it and let it get damaged.
>
>
> "Shervin Shapourian" <ShShapourian@.hotmail.com> wrote in message news:<vqofb5e8rl3k97@.corp.supernews.com>...
> > Take a look at IDENTITY (Property) in "SQL Server Books Online".
> > "Sumanth Suri" <sumant_suri@.hotmail.com> wrote in message
> > news:a3007893.0311071034.54617b6b@.posting.google.c om...
> > > Hi,
> > > I want to setup one of the fields in a table so it increments
> > > sequentially(int data type). i.e the first record should be record 1
> > > and the second one should be 2 and so on. This field will also be the
> > > key field. I am new to SQL and don't know how to do this.
> > > I am using SQL server 2000.
> > > Thanks for the help in advance.
> > > > -S|||>> Celko, Don't expect any royalty from this beginner! <<

What I used to get from beginners was consulting gigs, to clean up the
mess they made when their company has problems. Those jobs pay MUCH
better than royalties :)

Using IDENTITY as a primary key is a sign that there is no data model,
only an imitation of a sequential file system. Since this "magic,
all-purpose, one-size-fits-all" pseudo-identifier exists only as a
result of the physical state of a particular piece of hardware at a
particular time as read by the current release of a particular database
product, how do you verify that an entity has such a number in the
reality you are modeling?

You will see newbies who design tables like this:

CREATE Drivers
(driver_id IDENTITY (1,1) NOT NULL PRIMARY KEY,
ssn CHAR(9) NOT NULL REFERENCES Personnel(ssn),
vin CHAR(17) NOT NULL REFERENCES Motorpool(vin));

Now input data and submit the same row a thousand times, a million
times. Your data integrity is trashed. The natural key was this:

CREATE Drivers
(ssn CHAR(9) NOT NULL REFERENCES Personnel(ssn),
vin CHAR(17) NOT NULL REFERENCES Motorpool(vin),
PRIMARY KEY (ssn, vin));

If you want to enforce a rule that a car can have one driver:

CREATE Drivers
(ssn CHAR(9) NOT NULL REFERENCES Personnel(ssn),
vin CHAR(17) NOT NULL PRIMARY KEY
REFERENCES Motorpool(vin));

Now you are REALLY thinking about relations and keys instead of 1950's
sequential record numbering. Go further and add DRI:

CREATE Drivers
(ssn CHAR(9) NOT NULL
REFERENCES Personnel(ssn)
ON DELETE CASACADE
ON UPDATE CASACADE,
vin CHAR(17) NOT NULL PRIMARY KEY
REFERENCES Motorpool(vin)
ON DELETE CASACADE
ON UPDATE CASACADE,
PRIMARY KEY (ssn, vin));

Adding an IDENTITY column to either of these tables as a candidate key
would be dangerously redundant; one query uses the IDENTITY and another
uses the real key, and like a man with two watches, you are never sure
what time it is.

Researching the CHECK constraints you need for a VIN or SSN will take a
few days -- but newbies only want "quick and magic answers that solve
all the problems" and do not bother doing the real work.

Finally, an appeal to authority, with a quote from Dr. Codd: "..Database
users may cause the system to generate or delete a surrogate, but they
have no control over its value, nor is its value ever displayed to them
..."(Dr. Codd in ACM TODS, pp 409-410) and Codd, E. (1979), Extending
the database relational model to capture more meaning. ACM Transactions
on Database Systems, 4(4). pp. 397-434.

This means that a surrogate ought to act like an index; created by the
user, managed by the system and NEVER seen by a user. That means never
used in queries, DRI or anything else that a user does.

Codd also wrote the following:

"There are three difficulties in employing user-controlled keys as
permanent surrogates for entities.

(1) The actual values of user-controlled keys are determined by users
and must therefore be subject to change by them (e.g. if two companies
merge, the two employee databases might be combined with the result that
some or all of the serial numbers might be changed.).

(2) Two relations may have user-controlled keys defined on distinct
domains (e.g. one uses social security, while the other uses employee
serial numbers) and yet the entities denoted are the same.

(3) It may be necessary to carry information about an entity either
before it has been assigned a user-controlled key value or after it has
ceased to have one (e.g. and applicant for a job and a retiree).

These difficulties have the important consequence that an equi-join on
common key values may not yield the same result as a join on common
entities. A solution - proposed in part [4] and more fully in [14] - is
to introduce entity domains which contain system-assigned surrogates.
Database users may cause the system to generate or delete a surrogate,
but they have no control over its value, nor is its value ever displayed
to them...." (Codd in ACM TODS, pp 409-410).

References

Codd, E. (1979), Extending the database relational model to capture more
meaning. ACM Transactions on Database Systems, 4(4). pp. 397-434

--CELKO--
===========================
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||It's not always consecutive. So if it's important to you just forget
IDENTITY.
Identity is a means just like many other things in SQL, if you chose the
right tool for your problem you won't regret it. It's not a silver bullet
but it will help you if you use it in the right place.

Good luck,
Shervin

"Sumanth Suri" <dangerousminds_17@.yahoo.com> wrote in message
news:2e121621.0311111136.5c401fd@.posting.google.co m...
> how would you protect the behavior of IDENTITY?
> Shervin and wangkhar thanks for the help.
> Celko, Don't expect any royalty from this beginner!!
> Wangkhar@.yahoo.com (WangKhar) wrote in message
news:<bb269444.0311110220.539cf94d@.posting.google.com>...
> > Dont listen to Celko - his is too pr0 :p
> > go with the identity - but beware some of its behaviour, and protect
> > it carefully, it is not terribly robust and can totally shaft your
> > data relationships if you use it and let it get damaged.
> > "Shervin Shapourian" <ShShapourian@.hotmail.com> wrote in message
news:<vqofb5e8rl3k97@.corp.supernews.com>...
> > > Take a look at IDENTITY (Property) in "SQL Server Books Online".
> > > > "Sumanth Suri" <sumant_suri@.hotmail.com> wrote in message
> > > news:a3007893.0311071034.54617b6b@.posting.google.c om...
> > > > Hi,
> > > > I want to setup one of the fields in a table so it increments
> > > > sequentially(int data type). i.e the first record should be record 1
> > > > and the second one should be 2 and so on. This field will also be
the
> > > > key field. I am new to SQL and don't know how to do this.
> > > > I am using SQL server 2000.
> > > > Thanks for the help in advance.
> > > > > > -S

I WANNA UPDATE IMAGE

UPDATE TDAV
SET FOTO=(SELECT FOTO FROM #temp_FOTO WHERE NOID=TDAV.NOID)
Where FOTO is Image field. This syntax is error. How to Update Image field?If the comparison is based on a column with unique values ( the column noid
in your case ), you can use t-SQL update statement like:
UPDATE tdav
SET foto = t.foto
FROM #temp t
WHERE t.noid = tdav.noid ;
Anith

Monday, March 12, 2012

I ran a update quey by mistake

With out any BEGIN Transaction statement , i ran a update query.

I had to update just one record using the "Where field='abc'"

But i happened to miss that. Is there any chance of recovery? can i use the transaction logs to bring back the records before the update?

A quick answer is appreciated.

Sahel

Hi Sahel.

No way to get it back directly using native Sql tools/operations without performing some restore type operations.

Best way may be, if you have a standard backup structure in place, take a log backup immediately, then restore a copy of your database side-by-side with the existing db (using a different db name), and restore logs up to the point in time right before you ran the update statement (see the STOPAT option of the RESTORE LOG statement), then update the existing table with the values that exist in the table(s) from the restored database.

There are some 3rd party applications that you could consider researching and using, although these aren't a supported solution generally speaking, so be sure to clarify/understand that before using them (Lumigent Log Explorer is one for example).

HTH

I only want the first 50 bytes of the filed :(

My database has chinese characters in.
Eventually I need to only get the first 50 bytes of the data field, but somehow, I use len('==data==',50), it would catch 50 chinese characters which make 100 bytes ...
can anyone help me?
Thank you very much no matter what the result is ;)I'm not sure exactly what you want, so these are guesses. If you want the first 50 characters of an NCHAR, then you can use Left(@.v, 50). If you want the first 50 bytes of it, you can use Left(@.v, 25).
If you want something different... Post again with a better description and we'll take another shot!

-PatP

I only get the first character of the field returned .. what am i doing wrong ?

here is my business/data object for some reason I only get the first character back, say value is Charlie, I only get C

 
public string GetUserName(long UserId) {try {string userName; DiscussionDB data =new DiscussionDB(); List paramlist =new List(); paramlist.Add(data.CreateParameter("@.UserId", UserId)); paramlist.Add(data.CreateParameter("@.UserName","", ParameterDirection.Output, DbType.String, 20)); data.ExecuteNonQuery("dbo.Discussion_User_Name",ref paramlist); userName = paramlist[1].Value.ToString();return userName; }catch {throw; } }ALTER PROCEDURE [dbo].[Discussion_User_Name]@.UserId bigint,@.UserName varchar(20) outputASSET NOCOUNT ONSET @.UserName = (Select [Name] from Discussion_Member WHERE UserID = @.UserID)if (@.UserNameis null or @.UserName ='')BEGIN SET @.UserName = (Select UserName from Membership_User WHERE UserID = @.UserID)END

hello,

It does not seem that thre is anything wrong with the code.

Have you checked the size of the columns "Name" and "UserName" in Discussion_Member and/or Membership_User ?

hope this helps?

regards,

g

|||

If you run the stored procedure using the sql server tools, does it return the correct result?

|||

yes when I run the SP in MS sever 2005 studio, I get the full field ... e.g Charlie

|||

You need to set the size of @.UserName, the default is 1. There's a size property toIDbDataParameter that you need to set (it looks like your DiscussionDB is wrapping IDbDataParameter and some other stuff)

|||

I tried wording your suggestion in my code by I can't seem to figure it out

I was thinking that the 20in the code below was giving the size

paramlist.Add(data.CreateParameter("@.UserName","", ParameterDirection.Output, DbType.String, 20));

|||

I thought I got this working but I was wrong

I am still having this issue, here is my last code

public string GetUserName(long UserId) {try {string userName; DiscussionDB data =new DiscussionDB(); List paramlist =new List(); paramlist.Add(data.CreateParameter("@.UserId", UserId)); paramlist.Add(data.CreateParameter("@.UserName","", ParameterDirection.Output, DbType.String, 15)); paramlist[1].Size = 15; data.ExecuteNonQuery("dbo.Discussion_User_Name_Fetch",ref paramlist); userName = paramlist[1].Value.ToString();return userName; }catch {throw; } }

Wednesday, March 7, 2012

i need to find a table in my DB how to do it will QA

i have a app that runs on sql. i need to fine a table in it to make
changes. the table should have a field in it call translations patterns"
in it. what the cmds for QA do i use and what else do i need to do to see
whats this table tide to. Please help
James Grace
System Engineer /Professional Srvc.
MCSE MCSA MCDBA CCNA CCNP CQS
You could use the Object Search feature in Query Analyzer. Just open QA, hit
F4 to oben Object Search, type the column name into the Object Name textbox
and select Column checkbox and hit Find Now.
HTH
Jasper Smith (SQL Server MVP)
http://www.sqldbatips.com
I support PASS - the definitive, global
community for SQL Server professionals -
http://www.sqlpass.org
"AA" <jgrace@.digitelusa.net> wrote in message
news:eKg1tz2VFHA.3540@.TK2MSFTNGP15.phx.gbl...
>i have a app that runs on sql. i need to fine a table in it to make
>changes. the table should have a field in it call translations patterns"
>in it. what the cmds for QA do i use and what else do i need to do to see
>whats this table tide to. Please help
> --
> James Grace
> System Engineer /Professional Srvc.
> MCSE MCSA MCDBA CCNA CCNP CQS
>
>
|||Hi,
You could also do a search in INFORMATION_SCHEMA.columns view.
SELECT COLUMN_NAME,TABLE_NAME
FROM INFORMATION_SCHEMA.columns
WHERE COLUMN_NAME like 'translations%'
You could also query syscolumns system table (Not recommended)
Thanks
Hari
SQL Server MVP
"AA" <jgrace@.digitelusa.net> wrote in message
news:eKg1tz2VFHA.3540@.TK2MSFTNGP15.phx.gbl...
>i have a app that runs on sql. i need to fine a table in it to make
>changes. the table should have a field in it call translations patterns"
>in it. what the cmds for QA do i use and what else do i need to do to see
>whats this table tide to. Please help
> --
> James Grace
> System Engineer /Professional Srvc.
> MCSE MCSA MCDBA CCNA CCNP CQS
>
>
|||Try AgileInfoSoftware's DataStudio, it has very powerful search features.
Evaluation is free and can be downloaded at http://www.AgileInfoLLC.com
John
Senior Support Engineer
MCSD, MCSD.NET, SCJP, SCJD, OCDBA
"AA" <jgrace@.digitelusa.net> wrote in message
news:eKg1tz2VFHA.3540@.TK2MSFTNGP15.phx.gbl...
>i have a app that runs on sql. i need to fine a table in it to make
>changes. the table should have a field in it call translations patterns"
>in it. what the cmds for QA do i use and what else do i need to do to see
>whats this table tide to. Please help
> --
> James Grace
> System Engineer /Professional Srvc.
> MCSE MCSA MCDBA CCNA CCNP CQS
>
>

I need to change the name of a field...

I need to change the name of a field in a db hoy can I do soUSE <db name>
GO
EXEC sp_rename '<table name>.[org. field name]', '<new field name>', 'COLUMN'
GO

Friday, February 24, 2012

I need Optimised duplicate finding query

I have a query which is like this
Select field a, field b,field c, field d from table1 where field d not in
(select distinct field d from table 2)
Table 1 has 35000 records
Table 2 has 12391876 records
Field d is of type varchar.
If there is any duplicate to be found in table 2 then the insertion from
table 1 to table 2 will not happen.
I need this query to be get optimised.Hi
DECLARE @.rowcount INT
SELECT Field1,COUNT(*) FROM Table2
GROUP BY Field1
HAVING COUNT(*)>1
SET @.rowcount =@.@.ROWCOUNT
IF @.rowcount >0 --Do exist duplicate rows
.........
"Cynthia" <Cynthia@.discussions.microsoft.com> wrote in message
news:CDCF5DF6-52FA-4D80-AAED-1F3803720972@.microsoft.com...
>I have a query which is like this
> Select field a, field b,field c, field d from table1 where field d not in
> (select distinct field d from table 2)
>
> Table 1 has 35000 records
> Table 2 has 12391876 records
> Field d is of type varchar.
>
> If there is any duplicate to be found in table 2 then the insertion from
> table 1 to table 2 will not happen.
>
> I need this query to be get optimised.
>|||I understand that the below query is used for finding out a duplicate value
in table2.
Note : field d contains <FILE NAME> . if there are 20 records in a file then
20 records will have the same filename and so on. A group of files will be
imported to the temporary table (table 1). Before inserting it to the main
table (table 2) a check is done whether that file is existing in the main
table. If it is existing then the insertion process will not done in order t
o
avoid duplicate file being entered into the main table.
We use the below said query given by me for this task.
So I need a optimised query.
"Uri Dimant" wrote:

> Hi
> DECLARE @.rowcount INT
> SELECT Field1,COUNT(*) FROM Table2
> GROUP BY Field1
> HAVING COUNT(*)>1
> SET @.rowcount =@.@.ROWCOUNT
> IF @.rowcount >0 --Do exist duplicate rows
> ..........
> "Cynthia" <Cynthia@.discussions.microsoft.com> wrote in message
> news:CDCF5DF6-52FA-4D80-AAED-1F3803720972@.microsoft.com...
>
>|||> So I need a optimised query.
CREATE indexes to optimize your query
http://www.sql-server-performance.c...red_indexes.asp
http://www.sql-server-performance.c...red_indexes.asp
http://www.sql-server-performance.c...ing_indexes.asp
"Cynthia" <Cynthia@.discussions.microsoft.com> wrote in message
news:2B4DD3B0-5BFE-4984-9726-9036457E8EA1@.microsoft.com...
>I understand that the below query is used for finding out a duplicate value
> in table2.
> Note : field d contains <FILE NAME> . if there are 20 records in a file
> then
> 20 records will have the same filename and so on. A group of files will be
> imported to the temporary table (table 1). Before inserting it to the main
> table (table 2) a check is done whether that file is existing in the main
> table. If it is existing then the insertion process will not done in order
> to
> avoid duplicate file being entered into the main table.
> We use the below said query given by me for this task.
> So I need a optimised query.
> "Uri Dimant" wrote:
>|||You might try using a not exists instead of not in. Not in will select all
12,391,876 rows from table2 then order them and summarize them, which
requires a fiar amount of in memory processing. The Not exists will check
table2 for each row in table1, meaning a maximum of 35,000 lookups. Note,
this will be faster if you have an index on table2.fieldd, but may be much
slower is this index does not exist.
Select fielda, fieldb,fieldc, fieldd from table1 t1 where not exists
(select 1 from table2 t2 where t2.fieldd = t1.fieldd)
"Cynthia" <Cynthia@.discussions.microsoft.com> wrote in message
news:CDCF5DF6-52FA-4D80-AAED-1F3803720972@.microsoft.com...
> I have a query which is like this
> Select field a, field b,field c, field d from table1 where field d not in
> (select distinct field d from table 2)
>
> Table 1 has 35000 records
> Table 2 has 12391876 records
> Field d is of type varchar.
>
> If there is any duplicate to be found in table 2 then the insertion from
> table 1 to table 2 will not happen.
>
> I need this query to be get optimised.
>

I need help with the following (SQL Team Cross Post)

I am trying to setup a shape, shape attributes and calculate the cross
sectional area using the formula specified in the tbShapes.Formula field.
See the code below.

What this does is convert the formula

(Width * Flange) + (((Height - Flange) * Leg) * Count)

to

(108 * 4) + (((36 - 4) * 5) *2)

Now I need to calculate the expression above, but the
expression is a varchar string.

Any help?

USE NORTHWIND
GO

SET NOCOUNT ON
CREATE TABLE [dbo].[tbProductCodes] (
[ProductCode] [int] NOT NULL ,
[fkAccountID] [int] NOT NULL ,
[Product] [varchar] (50) NOT NULL ,
[fkShapeID] [int] NOT NULL
) ON [PRIMARY]
GO

INSERT INTO tbProductCodes (ProductCode, fkAccountID, Product, fkShapeID)
SELECT 2001, 1, 'New Product', 1
GO

CREATE TABLE [dbo].[tbProductTemplateAttributeValues] (
[fkTemplateID] [int] NOT NULL ,
[fkAttributeID] [int] NOT NULL ,
[AttributeValue] [float] NOT NULL
) ON [PRIMARY]
GO

INSERT INTO tbProductTemplateAttributeValues (fkTemplateID, fkAttributeID, AttributeValue)
SELECT 1, 1, 108 UNION ALL
SELECT 1, 2, 36 UNION ALL
SELECT 1, 3, 4 UNION ALL
SELECT 1, 4, 5 UNION ALL
SELECT 1, 5, 2
GO

CREATE TABLE [dbo].[tbProductTemplates] (
[TemplateID] [int] NOT NULL ,
[fkProductCode] [int] NOT NULL ,
[Template] [varchar] (50) NOT NULL ,
[fkMixID] [int] NULL
) ON [PRIMARY]
GO

INSERT INTO tbProductTemplates (TemplateID, fkProductCode, Template, fkMixID)
SELECT 1, 2001, 'ProductTemplate', 1
GO

CREATE TABLE [dbo].[tbShapeAttributes] (
[AttributeID] [int] NOT NULL ,
[fkShapeID] [int] NOT NULL ,
[Attribute] [varchar] (50) NOT NULL
) ON [PRIMARY]
GO

INSERT tbShapeAttributes (AttributeID, fkShapeID, Attribute)
SELECT 1, 1, 'Width' UNION ALL
SELECT 2, 1, 'Height' UNION ALL
SELECT 3, 1, 'Flange' UNION ALL
SELECT 4, 1, 'Leg' UNION ALL
SELECT 5, 1, 'Count'
GO

CREATE TABLE [dbo].[tbShapes] (
[ShapeID] [int] NOT NULL ,
[Shape] [varchar] (50) NOT NULL ,
[Formula] [varchar] (100) NULL
) ON [PRIMARY]
GO

INSERT INTO tbShapes (ShapeID, Shape, Formula)
SELECT 1, 'Double T', '(Width * Flange) + (((Height - Flange) * Leg) * Count)'
GO

CREATE PROCEDURE usp_shapes_GetCrossSection

@.iTemplate int,
@.cResult varchar (500) OUTPUT

AS

declare @.cAttribute varchar(50),
@.fAttribute float

-- Get the formula for the templates shape
SELECT @.cResult = s.Formula
FROM tbShapes AS s INNER JOIN tbProductCodes AS pc
ON s.ShapeID = pc.fkShapeID
INNER JOIN tbProductTemplates AS pt
ON pc.ProductCode = pt.fkProductCode
WHERE pt.TemplateID = @.iTemplate

SELECT @.cResult AS Formula

DECLARE AttributeCursor CURSOR FOR
SELECT sa.Attribute,
av.AttributeValue
FROM tbProductTemplateAttributeValues AS av INNER JOIN tbShapeAttributes AS sa
ON av.fkAttributeID = sa.AttributeID
WHERE av.fkTemplateID = @.iTemplate

OPEN AttributeCursor
FETCH NEXT FROM AttributeCursor INTO @.cAttribute, @.fAttribute
while(@.@.FETCH_STATUS = 0)
BEGIN
SELECT @.cResult = REPLACE(@.cResult, @.cAttribute, CAST(@.fAttribute AS VarChar))
FETCH NEXT FROM AttributeCursor INTO @.cAttribute, @.fAttribute
END

SELECT @.cResult AS NewFormula

CLOSE AttributeCursor
DEALLOCATE AttributeCursor
GO

-- Test stored proc

declare @.iTemplate int, @.fResult float

SET @.iTemplate = 1
EXECUTE usp_shapes_GetCrossSection @.iTemplate, @.fResult OUTPUT
SELECT @.fResult AS Result
GO

drop table [dbo].[tbProductCodes]
GO

drop table [dbo].[tbProductTemplateAttributeValues]
GO

drop table [dbo].[tbProductTemplates]
GO

drop table [dbo].[tbShapeAttributes]
GO

drop table [dbo].[tbShapes]
GO

DROP PROCEDURE usp_shapes_GetCrossSection
GO

Mike BMike, I guess I still don't get why your application requires this. Broken down, what you are doing is taking values stored as integers, running them through a procedure that casts them as characters buried in a string, and then looking for a procedure that strips them back out again?

It sound kind of circular.

Without too much difficulty, you could write a store procedure specific to the formula you gave that will parse the values out based on their positional relationship to the parenthesis characters, but it would not be a general solution. It would not work for any other formula.

If you can limit your operations to add, subtract, multiply, and divide, and if you can ensure that your formula will contain plenty of parenthesis to specify operation precedence, then without you might be able to write a recursive function that would be a general solution for simple formulas.|||Originally posted by blindman
Mike, I guess I still don't get why your application requires this. Broken down, what you are doing is taking values stored as integers, running them through a procedure that casts them as characters buried in a string, and then looking for a procedure that strips them back out again?

It sound kind of circular.

Without too much difficulty, you could write a store procedure specific to the formula you gave that will parse the values out based on their positional relationship to the parenthesis characters, but it would not be a general solution. It would not work for any other formula.

If you can limit your operations to add, subtract, multiply, and divide, and if you can ensure that your formula will contain plenty of parenthesis to specify operation precedence, then without you might be able to write a recursive function that would be a general solution for simple formulas.

Thanks for your reply BlindMan, but a couple of people at SQL Team found a solution.

declare @.iTemplate int, @.fResult varchar(500)

SET @.iTemplate = 1
EXECUTE usp_shapes_GetCrossSection @.iTemplate, @.fResult OUTPUT

DECLARE @.stmt nvarchar(4000)
DECLARE @.param nvarchar(4000)
DECLARE @.Eval int

SET @.stmt='SET @.StmResult = ' + @.fResult
SET @.Param='@.StmResult int out'

EXEC sp_executesql @.stmt, @.Param, @.Eval OUT

SELECT @.Eval

Using the dynamic SQL the Equation can be computed. Anyway, if you would like to see the post it is at:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=34179

Mike B|||OK, that was a cool solution. Dynamic SQL.

Sunday, February 19, 2012

I need help with Float datatype

I have a breakAmt field in my table that is a float datatype. The values
need to be in hours. So if employeeA took a break for 1 minute it should be
0.016. If EmployeeB had a 19 minute break it should be 0.316. If EmpC took
a 3 minute break I get the value 5.0000000000000003E-2. How can I convert
this to leave out the E-2'
The reson I need to maintain a float is because I need to extract these
values to a foxpro table that requires a float field. If I use a decimal
instead will the export bomb'
Thanks,
NinelIIRC the FLOAT datatype in FoxPro is an exact numeric, not at all the
same as SQL Server's FLOAT, which is an approximate floating point
type. I see no reason why you need to use FLOAT for this in SQL Server,
whatever the type in FoxPro.
If you want exact values then use an exact numeric datatype. If you
just want to *display* the value differently then do that in your
client application.
David Portas
SQL Server MVP
--|||According to
http://msdn.microsoft.com/library/e...pes.as
p
FoxPro's [float] is the same as FoxPro's [numeric], which looks
like a "floating" decimal to me. To cover the FoxPro range of
scale and precision use SQL Server's NUMERIC(30,10). If you
do not need this much range or precision, scale down to
NUMERIC(28,X) or NUMERIC(19,X), where X is the maximum
number of places after the decimal point you need.
Using 28 avoids some quirky things due to internal calculations
using 64-bit floating point values (I think), and also saves 4 bytes
per value. Using 19 saves yet another 4 bytes.
Steve Kass
Drew University
ninel gorbunov via webservertalk.com wrote:

>I have a breakAmt field in my table that is a float datatype. The values
>need to be in hours. So if employeeA took a break for 1 minute it should be
>0.016. If EmployeeB had a 19 minute break it should be 0.316. If EmpC took
>a 3 minute break I get the value 5.0000000000000003E-2. How can I convert
>this to leave out the E-2'
>The reson I need to maintain a float is because I need to extract these
>values to a foxpro table that requires a float field. If I use a decimal
>instead will the export bomb'
>Thanks,
>Ninel
>|||Take a look at the following script:
use pubs
go
declare @.fr float,@.fn float
set @.fn = 1
set @.fr=(@.fn/60)
print (@.fn/60)
set @.fn = 19
set @.fr=(@.fn/60)
print (@.fn/60)
set @.fn = 3
set @.fr=(@.fn/60)
print (@.fn/60)
go
HTH,
Thanks
ZULFIQAR SYED
http://zulfiqar.typepad.com
MCP
"ninel gorbunov via webservertalk.com" wrote:

> I have a breakAmt field in my table that is a float datatype. The values
> need to be in hours. So if employeeA took a break for 1 minute it should b
e
> 0.016. If EmployeeB had a 19 minute break it should be 0.316. If EmpC took
> a 3 minute break I get the value 5.0000000000000003E-2. How can I convert
> this to leave out the E-2'
> The reson I need to maintain a float is because I need to extract these
> values to a foxpro table that requires a float field. If I use a decimal
> instead will the export bomb'
> Thanks,
> Ninel
>

I need Help

Hi Freinds,
I need some help on SQL Server.
I need to create a trigger on the update of a particular field in a table.
This trigger has to perform some action after an hour since this field is updated.
Java has a sleep function, does SQL also have something like that.

Please (if ull can)Reply on my personal id.
parul.gulati@.india.birlasoft.com

Thanks and Regards,
ParulSQL Server has:

WAITFOR { DELAY 'time' | TIME 'time' }

The WAITFOR statement suspends the execution of a connection until either:

i) specified time interval has passed.
ii) specified time of day is reached.

Example:
WAITFOR DELAY '00:00:02'

However I would not use this within a trigger. Since a trigger is fired on a event (INSERT,UPDATE,DELETE), that event will also be suspend for an hour (your example), untill the trigger has completed.

If you need to perform some sort of action after an hour, look at:

1) use xp_cmdshell to call an external program which will sleep for the hour, then connect to the DB and perform the action.

2) Look at sp_OA procedures (sp_OACreate, sp_OAMethod, ...) which could be used to run a COM object program.

3) Have the trigger load a seperate table or set a flag indicating an action to be taken, then have a seperate stored procedure perform your work for you, the procedure could be scheduled using SQL Server's scheduler to run every 15 minutes or so.