Showing posts with label select. Show all posts
Showing posts with label select. Show all posts

Friday, March 30, 2012

how to change the data label in SQL?

I have the following SQL statement..

select month(dbo.udfAddUTCBias(start_date_time, 180)) as report_month, direction as direction, count(*) as total_records from traffic with (nolock) where dbo.udfAddUTCBias(start_date_time, 180) >= '2/24/2007' and dbo.udfAddUTCBias(start_date_time, 180) < DateAdd(dd, 1, '2/24/2007') group by month(dbo.udfAddUTCBias(start_date_time, 180)), direction

but the result of the direction field is 1 and 0..

however, I need to show inbound when the result is 0 and outbound when the result is 1 without changing the actual data in the table.

You could use CASE keyword: http://msdn2.microsoft.com/en-us/library/aa258235(SQL.80).aspx

select month(dbo.udfAddUTCBias(start_date_time, 180)) as report_month

, case direction

when 0 then 'inbound'

when 1 then 'outbound'

end

as direction

, count(*) as total_records from traffic with (nolock) where dbo.udfAddUTCBias(start_date_time, 180) >= '2/24/2007' and dbo.udfAddUTCBias(start_date_time, 180) < DateAdd(dd, 1, '2/24/2007') group by month(dbo.udfAddUTCBias(start_date_time, 180)), direction

Wednesday, March 28, 2012

How to change SQL Server Name

Hi all,

I have a server with machine name as ABC with SQL Server 2000 in it.

Executing Select @.@.Servername gave me ABC before but after i changed the Machine name to XYZ @.@.Servername is still showing ABC. can somebody tell me how to change the SQL Server name to That of the machine i.e XYZ.

This should help:

http://support.microsoft.com/kb/303774

|||Thank You Sir that was very helpful.

how to change server option for isolaiton level?

I'm having problem with locking in update and select.
my update takes long and select from clients happens all the time.
I know with NOLOCK in select or set transaction isolation level, I can
read data uncommited.
I want to know if there is an option I can change on server or
database
to change isolation level for all incoming connections.

thanks for your help in advance.AFAIK, you can't set READ UNCOMMITTED at the server level. This is
probably a good thing since one should read uncommitted data only in
specific situations where all off the ramifications have been fully
evaluated and understood.

--
Hope this helps.

Dan Guzman
SQL Server MVP

--------
SQL FAQ links (courtesy Neil Pike):

http://www.ntfaq.com/Articles/Index...epartmentID=800
http://www.sqlserverfaq.com
http://www.mssqlserver.com/faq
--------

"neo" <second714@.hotmail.com> wrote in message
news:155f8e7d.0311071340.6727ff6d@.posting.google.c om...
> I'm having problem with locking in update and select.
> my update takes long and select from clients happens all the time.
> I know with NOLOCK in select or set transaction isolation level, I can
> read data uncommited.
> I want to know if there is an option I can change on server or
> database
> to change isolation level for all incoming connections.
> thanks for your help in advance.|||Hi

To add to Dan's comment...

Are you wanting to make the database read only?

John

"neo" <second714@.hotmail.com> wrote in message
news:155f8e7d.0311071340.6727ff6d@.posting.google.c om...
> I'm having problem with locking in update and select.
> my update takes long and select from clients happens all the time.
> I know with NOLOCK in select or set transaction isolation level, I can
> read data uncommited.
> I want to know if there is an option I can change on server or
> database
> to change isolation level for all incoming connections.
> thanks for your help in advance.|||Thanks to Dan/John.

No I just wanted to allow dirty-read, not read-only db.

I thought there was an option in SQL to set db to allow read uncommited.
Maybe for SQL 7?

"John Bell" <jbellnewsposts@.hotmail.com> wrote in message news:<boieas$93o$1@.titan.btinternet.com>...
> Hi
> To add to Dan's comment...
> Are you wanting to make the database read only?
> John
> "neo" <second714@.hotmail.com> wrote in message
> news:155f8e7d.0311071340.6727ff6d@.posting.google.c om...
> > I'm having problem with locking in update and select.
> > my update takes long and select from clients happens all the time.
> > I know with NOLOCK in select or set transaction isolation level, I can
> > read data uncommited.
> > I want to know if there is an option I can change on server or
> > database
> > to change isolation level for all incoming connections.
> > thanks for your help in advance.|||Hi

This is not something you would want do as a default, and when you do
require it, then it has to be a concious decission to allow this;
therefore not having it at server level or as a default for the
connection is probably a good thing. You can always set it for the
connection/session.

John

second714@.hotmail.com (neo) wrote in message news:<155f8e7d.0311101122.ca78281@.posting.google.com>...
> Thanks to Dan/John.
> No I just wanted to allow dirty-read, not read-only db.
> I thought there was an option in SQL to set db to allow read uncommited.
> Maybe for SQL 7?
>
> "John Bell" <jbellnewsposts@.hotmail.com> wrote in message news:<boieas$93o$1@.titan.btinternet.com>...
> > Hi
> > To add to Dan's comment...
> > Are you wanting to make the database read only?
> > John
> > "neo" <second714@.hotmail.com> wrote in message
> > news:155f8e7d.0311071340.6727ff6d@.posting.google.c om...
> > > I'm having problem with locking in update and select.
> > > my update takes long and select from clients happens all the time.
> > > I know with NOLOCK in select or set transaction isolation level, I can
> > > read data uncommited.
> > > I want to know if there is an option I can change on server or
> > > database
> > > to change isolation level for all incoming connections.
> > > > thanks for your help in advance.|||Thanks,
one more thing,
what about Query analyzer?
is there any way not to run "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"
everytime in Query Analyzer?|||Hi

As far as I know, you can't do this, configurable options appear on
the tools/options dialogues and that is not one of them. If it was you
could use a specific configuration file. The only thing I can suggest
it to put it in a template.

John

second714@.hotmail.com (neo) wrote in message news:<155f8e7d.0311111702.4609998d@.posting.google.com>...
> Thanks,
> one more thing,
> what about Query analyzer?
> is there any way not to run "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"
> everytime in Query Analyzer?

Wednesday, March 21, 2012

how to change date format in a select statement

when i use this command in a aspx file

"SELECT DISTINCT Format$([dbo.classgiven.classdate], 'mm/yyyy') AS monthyear,{.......................

'Format$' is not a recognized function name.

so how do i change date from mm/dd/yyyy to mm/yyyy

Check out the CAST and CONVERT functions in SQL BOL. They have a listing of all the possible combinations of formatting you can do for datetime values.|||

Hi~

Try this:

SELECTRIGHT(CONVERT(VARCHAR(10), Column_Name, 103), 7)AS [MM/YYYY]from Table_Name
Hope it helps.

Monday, March 19, 2012

How to catch errors

I have an statement
SELECT * from lkSFSAHousing where id = @.answer
Problem is that id is int and some times @.answer is not int
how would I catch either the error or not even get into not calling
this statement if @.answer is not digit (1 or 2 or 1000)
Can anybody help?
ThanksOn Feb 8, 11:59 am, "Sehboo" <MasoodAd...@.gmail.com> wrote:
> I have an statement
> SELECT * from lkSFSAHousing where id = @.answer
> Problem is that id is int and some times @.answer is not int
> how would I catch either the error or not even get into not calling
> this statement if @.answer is not digit (1 or 2 or 1000)
> Can anybody help?
> Thanks
Ideally, you should have some validation in place at the point where
@.answer is assigned a value. Where/how is this being done?

Monday, March 12, 2012

How to capture return value from 'execute'

declare @.table varchar(100);

declare @.q varchar(100);

declare @.key bigint;

select @.table = 'key_table';

select @.q = 'select key from ' + @.table;

select @.key = exec(@.q); -> not working.

Check in books online; you'll find that the string execute version of the EXEC command does not provide the same ability to capture a return value as does the execution of a stored procedure. Sorry.|||

In that case, can you suggest an alternative for the my requirement. I want to get the return value of a select statement constructed dynamically.

Thanks,

|||

create a temp table and use this type

insert into #tempTable

exec ( @.yourExecString )

Also, understand that using the EXEC ( @.yourExecString ) syntax might leave you subject to SQL INJECTION attacks.

|||

Use sp_executesql instead EXEC(...). You can use output paraeters with this sp.

declare @.table sysname;

declare @.q nvarchar(100);

declare @.key bigint;

select @.table = N'key_table';

select @.q = 'select @.key = key from dbo.[' + @.table + N']';

exec sp_executesql @.q, N'@.key bigint output', @.key output;

select @.key

go

Be careful with sql injection.

The Curse and Blessings of Dynamic SQL

http://www.sommarskog.se/dynamic_sql.html

AMB

how to capture o/p of SELECT .. FOR XML AUTO.

Hi,
Can u please tell me how can i store o/p of following query into a variable
and process it.
"SELECT TOP 1 FIRSTNAME, LASTNAME FROM PATIENT FOR XML AUTO"
Thanks
Gopinath M.
"Gopinath Munisifreddy" <Gopinath@.Microsoft.com> wrote in message
news:eaMr75zEEHA.3336@.TK2MSFTNGP12.phx.gbl...
> Hi,
> Can u please tell me how can i store o/p of following query into a
variable
> and process it.
> "SELECT TOP 1 FIRSTNAME, LASTNAME FROM PATIENT FOR XML AUTO"
You can't store the results of a for xml query just within SQL. The XML is
created by the provider.
Bryant
|||There are some ugly workarounds using the sp_OA stored procedures.
In SQL Server 2005 (beta2 comming soon, watch this space for nomination
registration), you will be able to do so.
Best regards
Michael
"Bryant Likes" <bryant@.suespammers.org> wrote in message
news:Ogsvi70EEHA.3568@.tk2msftngp13.phx.gbl...
> "Gopinath Munisifreddy" <Gopinath@.Microsoft.com> wrote in message
> news:eaMr75zEEHA.3336@.TK2MSFTNGP12.phx.gbl...
> variable
> You can't store the results of a for xml query just within SQL. The XML is
> created by the provider.
> --
> Bryant
>

How to call talbe/SP from Linked server with out database and user

Dear Friends,
Usually we call tabal and SP like given below.
select * from [linkedserver].[database].[dbo].[TableName]
EXEC [linkedserver].[database].[dbo].usp_storedprocedure
but I like to all with out database and username.
I tryed like below
select * from [linkedserver]...[TableName]
OR
select * from [linkedserver]..[user].[TableName]
It's gives error
Server: Msg 7313, Level 16, State 1, Line 1
Invalid schema or catalog specified for provider 'MSDASQL'.
OLE DB error trace [Non-interface error: Invalid schema or catalog
specified for the provider.].
Please help me to achive this.
Thasks and regards,
Rajesh
On Wed, 14 Sep 2005 07:57:08 -0700, Rajesha wrote:

>Dear Friends,
>Usually we call tabal and SP like given below.
> select * from [linkedserver].[database].[dbo].[TableName]
> EXEC [linkedserver].[database].[dbo].usp_storedprocedure
>but I like to all with out database and username.
>I tryed like below
>select * from [linkedserver]...[TableName]
>OR
>select * from [linkedserver]..[user].[TableName]
>It's gives error
>Server: Msg 7313, Level 16, State 1, Line 1
>Invalid schema or catalog specified for provider 'MSDASQL'.
>OLE DB error trace [Non-interface error: Invalid schema or catalog
>specified for the provider.].
>Please help me to achive this.
>Thasks and regards,
>Rajesh
Hi Rajesh,
You can't leave out the databasename. A linked server might hold more
than one database, so you have to specify that part.
I believe that you can leave out the owner, but I'm not sure, and I
can't test that right now. However, it is recommended that you always
include the owner. This helps SQL Server find the object more quickly,
and it helps reduce the number of recompiles.
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)

Wednesday, March 7, 2012

How To Call A Procedure While Declaring A Cursor

HI,
WHILE DECLARING A CURSOR TO SELECT RECORDS FROM A TABLE WE NORMALLY WRITE :-

DECLARE CUR_NAME CURSOR
FOR SELECT * FROM CLEANCUSTOMER

BUT SAY, IF I HAVE WRITTEN A SIMPLE PROCEDURE CALLED AS MY_PROC :-

CREATE PROCEDURE MY_PROC
AS
SELECT A.INTCUSTOMERID,A.CHREMAIL,B.INTPREFERENCEID,C.CHR PREFERENCEDESC
FROM CLEANCUSTOMER A
INNER JOIN TRCUSTOMERPREFERENCE03JULY B
ON A.INTCUSTOMERID = B.INTCUSTOMERID
INNER JOIN TMPREFERENCE C
ON B.INTPREFERENCEID = C.INTPREFERENCEID
ORDER BY B.INTPREFERENCEID

WHICH IS RUNNING FINE AND GIVING ME THE REQUIRED DATA WHILE EXECUTING THE PROCEDURE :-

EXEC MY_PROC

BUT IF I WANT TO CALL THIS PROCEDURE MY_PROC WHILE DECLARING A CURSOR :-

I AM USING :-

DECLARE CHK_CUR CURSOR
FOR SELECT * FROM MY_PROC

WHICH IS GIVING AN ERROR "Invalid object name 'MY_PROC'."

AND IF I USE :-

DECLARE CHK_CUR CURSOR
FOR EXEC MY_PROC

WHICH IS GIVING AN ERROR "Incorrect syntax near the keyword 'EXEC'".

AND IF I USE :-

DECLARE CHK_CUR CURSOR
FOR CALL MY_PROC

WHICH IS GIVING AN ERROR "Incorrect syntax near 'CALL'. "

IS THERE ANY WAY BY WHICH I CAN FETCH RECORDS FROM THE STORED PROCEDURE?
HOW DO I DECLARE THE PROCEDURE WHILE WRITING THE CURSOR
PLS HELP.

I NEED THIS URGENTLY, I HAVE TO USE THE CURSOR TO FETCH THE RECORDS FROM THE SP,THAT'S HOW THEY WANT IT.I CAN'T HELP IT AND I DON'T KNOW HOW

THANKSDo a insert inot temp table and then use the temp table to declare the cursor|||/*
As far as i know, there is only one way, you must create a temporary table, for example:
*/

Create Proc Caller
As
Create Table #temp (INTCUSTOMERID [FieldType],
CHREMAIL [FieldType], INTPREFERENCEID [FieldType],
CHRPREFERENCEDESC [FieldType])
Declare CHK_CUR For Select a.INTCUSTOMERID From #temp a
Insert Into #temp (INTCUSTOMERID, CHREMAIL, INTPREFERENCEID,
CHRPREFERENCEDESC) Exec MY_PROC

/*Do what ever you want with your cursor|||Hi,
Thanks Enigma And Sneaky Pie For The Quick Replies ,but The Problem Still Lies And It Has Not Helped Me Much.

The Thing Is It Might Be Possible That I Have Not Written It Down
Properly Or You Might Not Have Understood What I Have Wanted To Ask From You.

First Of All I Don't Want To Declare A Cursor Inside A Procedure For Some Reasons Out Here.

Second,i Want To Declare A Cursor Outside The Procedure And Then Call The Procedure From The Cursor.

Third,as You Said That I Should Use A Temp Table,which Is Not Possible Cause The Temp Table Is Not Present Outside The Procedure In Which It Is Created,i Might Be Wrong ,but Pls Tell Me So Then.

Fourth, I Can Go For A Permanent Table ,but It Consumes Too Much
Space,which Is A Constraint In Our Case.

Pls ,look Into The Above Scenario And Help Me Out With It.i Personally Think That It Should Be A Nobrainer,but Somehow It Has Become A Nightmare For Me.

Pls Look Into It As Soon As Possible As I Am Really Feeling The Heat On This Now.

Thanks.|||But the way with the temporary table is the only solution with procs.
Create the #table and after that you are able to create a cursor fetching this #table. If you need a result after some changes or calculations with the cursor data, you need a second #table. At the end return the data of the second #table.

There is, maybe, an other way, but it works with funtions, not with procs. You can create a function that returns a cursor.|||I think Enigma was getting at something like:CREATE TABLE #procResults (
column1 -- whatever
column2 -- etc
)

DECLARE scum CURSOR FOR SELECT
column1, column2
FROM #procResultsDoes that make more sense?

-PatP|||HI,
tHANKS SNEAKY PIE ,BUT I THINK PAT GOT IT RIGHT ABOUT WHAT I WANT : - BUT THE PROBLEM STILL PERSISTS.

I AM GETTING :-

IF,
I AM USING :-

DECLARE CHK_CUR CURSOR
FOR SELECT * FROM MY_PROC

WHICH IS GIVING AN ERROR "Invalid object name 'MY_PROC'."

AND IF I USE :-

DECLARE CHK_CUR CURSOR
FOR EXEC MY_PROC

WHICH IS GIVING AN ERROR "Incorrect syntax near the keyword 'EXEC'".

AND IF I USE :-

DECLARE CHK_CUR CURSOR
FOR CALL MY_PROC

WHICH IS GIVING AN ERROR "Incorrect syntax near 'CALL'. "

IS THERE ANY WAY TO CALL THE PROCEDURE FROM A CURSOR AND SAVE THE RESULTS OF THE PROCEDURE IN A VARICABLE OR SOMETHING.
BUT REMEMBER ONLY AFTER THE PROCEDURE IS CALLED FROM THE CURSOR.

THANKS.|||Oops! My bad, I forgot an important step (sleep deprivation does funny things to me!). Let's try:CREATE TABLE #procResults (
column1 -- whatever
column2 -- etc
)

INSERT INTO #procResults -- The "missing link"
EXECUTE myProc

DECLARE scum CURSOR FOR SELECT
column1, column2
FROM #procResults-PatP|||Hi,

Fantastic !!! Right On !! Bull's Eye !!!!!

Got It ... Thanks To You... I Was Scratching My Skull Whole Of Last Week.

But,

Now Though, Things Are Running Fine ... It Is Giving :-

System Low On Resources
Affecting The Whole System .

Is There Any Way Or Any Settings That Could Be Changed. ?

So That I Can Allocate More Resources While The Cursor Is Running.

Thanks|||What is giving the messages? Are they in the Transact-SQL output, the SQL Server log, an NT log, or somewhere that I haven't thought of yet?

-PatP|||HI,

THE MESSAGES ARE FROM THE T-SQL OUTPUT :-

"SYSTEM LOW ON RESOURCES SOME OF THE RESULTS WOULD BE DROPPED."

THIS IS AFFECTING MY WHOLE SYSTEM... AFTER I RUN THE CURSORS

Is There Any Way Or Any Settings That Could Be Changed. ?

So That I Can Allocate More Resources While The Cursor Is Running.

Thanks|||Your choices are quite limited in that situation. You can upgrade the hardware (most likely RAM memory) to make more resources available, or stop other (non-essential) processes running on the same machine to free up the resources that they are using. Those are the only choices that I think might help.

-PatP|||OK...anyone want to ask WHY there's a CURSOR in the mix?

How many levels of nested cursors do you have?|||Hi,

I Don't Think My Ram Must Be A Problem Has It Is 256mb Ram And I Have Seen Stopping The Remaining Processes And Running Only This Processes Still It Gives A Problem.

Also, There Is Only One Level Of Cursors.

And The Data Contained In The Table Is Just Around 10,000 .so Shouldn't Be Problem.

So If Something About This Could Be Done Then It Would Be Fantastic.

Thanks.|||Don't use a Procedure use an inline table function:

CREATE FUNCTION dbo.fn_MY_PROC()
RETURNS TABLE
AS
RETURN (

SELECT TOP 100 PERCENT A.INTCUSTOMERID,A.CHREMAIL,B.INTPREFERENCEID,C.CHR PREFERENCEDESC
FROM CLEANCUSTOMER A
INNER JOIN TRCUSTOMERPREFERENCE03JULY B
ON A.INTCUSTOMERID = B.INTCUSTOMERID
INNER JOIN TMPREFERENCE C
ON B.INTPREFERENCEID = C.INTPREFERENCEID
ORDER BY B.INTPREFERENCEID

)

declare cursor cur as fast_forward local for
select * /*or whatever*/ from dbo.fn_MY_PROC()|||Hi,

Thanks,hanif For The Suggestion, But Yes I Will Have To Think On It On A Long -term Basis . About How To Convert All The Procs Into Functions .but Right Now Will Have To Stick On The Existing System To See How It Works.

Thanks.

Friday, February 24, 2012

how to calculate cost of a trigger?

I wanna used derived fields to improve select performance of my system.

How can I calculate the trigger cost in the system?

Triggers are resource intensive objects, you should look for alternatives before implementing them. You can run the profiler to find out the cost of any code you run through SQL Server. You will find the Profiler under tools in Management studio. Hope this helps.|||I wanna usedderived fields to improve select performance of my system.

How can I calculate the trigger cost in the system?

We are designing the DATA MODELand The TASK table it has two mutually exclusive fields.
WHOID > PersonID,OrganizationID
WHATID > DocumentID,EstateID,LeadID,RequirementID,

and on the Task UI we display the names of the Related EntityTypes and this causes us 10 inner/Joins to pull the data from database.

One of the designer in the team suggested putting derived fields such as
WHONAME > PersonName,OrganizationName
WHATNAME > DocumentName,EstateType,LeadName,RequirementName

So from performance perspective,We are really confused as putting triggers cause implicit locks on the system where as the other option causes 10 joins.

There is one to many relationship between WHOID and TASK(..3 related entitytypes mutually exclusive)
and also there is one to many relationship between WHATID and TASK(..7 related entitytypes mutually exclusive)

7 joins + 3 joins = 10 joins.

it is a really simple UI infact.
The Edit screen of TASK EDIT
--------------
Subject > char
FromDate > datetime
Todate > datetime
Priority > char
State > char
Email > char
Whoname> Related Person,Organization or Lead NAME
WhatName>Related Document,Estate,Requirement,Case,Oppurtunity Name ..etc

------
I would love not to have ten joins but the requirement forces us that way|||

What you need is simple DRI(declarative referenctial integrity) enabled on the tables in Management studio, so Updates will Cascade and if needed Deletes will Cascade. I know you need a DDL( data definition langauge) person in your team because a Table design comes down to files and association, while relationship is determined by upper and lower bound Cardinality. If you follow that most of your tables will disappear and what is now a JOIN will become a simple additional condition which in SQL Server can be added with the AND operator to a JOIN operation.

Some people do just DDL(data definition language) for a living. Run a search for DRI(declarative referential integerity) in SQL Server BOL (books online). Hope this helps.

|||

thanks caddre.that looks interesting.

http://www.cvalde.net/document/declaRefIntegVsTrig.htm

but I have a hard time understanding how it will change my WHONAME and WHATNAME.

if the it does it would be great.

|||

I could be wrong but what you have looks like objects to me because if those are two tables you need just two IDENTITY or it becomes a composite. Try the link below and download and install AdventureWorks 2005 most tables you need in a business application is in there. Look at the tables pay attention to the constraints and DRI (declarative referential integrity). Hope this helps.

http://www.microsoft.com/downloads/details.aspx?familyid=e719ecf7-9f46-4312-af89-6ad8702e4e6e&displaylang=en

|||

Is there a problem with the 10 joins?

Personally, I would just create a view to simplify the select statement that has all your required joins in it. Just make sure your tables are indexed properly, and you shouldn't have an issue.

|||

Hmmm I have tested it with 10 million records and the derived approach is 20X faster.

I really don't wanna use triggers but for now I'll just try the links caddre send.

|||

If you aren't displaying all 10 million rows at a time within the UI, you may find it beneficial to do your limiting select first, then doing the 10 joins once your have your limited resultset back, kinda like:

SELECT ...
FROM (Your limited query here)
JOIN ...
JOIN ...
JOIN ..

although why SQL Server isn't already doing that for you is odd. A bad query plan, or inaccurate statistics most likely. Before spending the time on trying to work around SQL, I'd first run your query through the tuning wizard and see what it comes up with, you may be suprised. If you've already done that, my appologies.

You want to try an indexed view approach as well, which may give you what you are looking for. Something like:

CREATE MyView WITH SCHEMABINDING AS

SELECT (Your 10 fields here),t1.Name,t2.Name,t3.Name,t4.Name,...
FROM MyTable mt
JOIN EntityRef t1 ON (mt.key=t1.key)
...

Then create a primary key on the view, then create your indexes (Whatever you are limiting/searching on)

You'll incur much of the same overhead as triggers though, so test your results.

|||

As a side note, Caddre has mentioned a lot of differing technologies, one of which is DRI. DRI by itself won't help to solve your issue, but by leveraging it, if possible, it could reduce the complexity of your database design, and increase your performance.

For example, take table1, and table2 here:

Table Name > Fields

Table1>EntityID,col1,col2,col3,col4...
Table2>EntityID,Name

Normally DRI is used to link both entityIDs in table1 and table2 in a foreign key relationship. This by itself will not gain you any performance at all, infact in many operations it will decrease overall performance substantially. However, if you redesign your tables, like so:

Table1>Name,col1,col2,col3,col4...
Table2>Name

Now by using DRI to maintain the relationship between Name (via a foreign key), then it's quite possible you will see a performance increase since you have just eliminated a join in your selects. Foreign keys can be used to "replicate" changes in the name field done in table2 to all records in table1 that use that name Now that's one VERY expensive update, but, it does insure that all instances in table1 that link to a particular name all use the exact same name. This is usually why you use identifiers in your base tables to begin with, and since those changes are very infrequent (Or should be), it's a decent trade off in performance, but you can make a pretty big mess of your database structure (and data) by taking this route if you aren't careful though. These in SQL Server are also called Cascading Deletes and Updates.

Using our above new schema, if you issue this:
UPDATE table2 SET Name='new value' where Name='old value'
SQL Server will actually do something like this:
BEGIN TRANSACTION
UPDATE table2 SET Name='new value' where Name='old value'
UPDATE table1 SET Name='new value' where Name='old value'
COMMIT TRANSACTION

With better error handling of course. If there are any errors, it's all rolled back, but it's called cascading be cause a delete in table2 would delete some records in table1, which in turn may delete some records in table3, etc.

Now with all that out of the way, you have to realize by replacing your small little ID field with a probably much larger field, sure you lose the join, but you've increased your row size. Indexes will be larger, and pages will contain less rows. Operations that require to scan large portions of your table will take longer, as well. So test a lot, on not just on what you need to do now, but think and test the ramifications on all your other queries as well.

|||

I have thought another method today which might be wrong ...instead of using DRI and triggers to maintain the data I am thinking about writing a class just for the purpose of putting data and updating data into my derived field.And I will tell from code behind that I need to update in anycase the update happens in my main tables of derived coloumns.

The advantages of this approach over triggers.

1.No implicit transactions

2.easy to debug

3.Faster than triggers

4.No unneccessary updates

5.Could write code to maintain and check the alldata.

Disadvantages I see

1.Triggers are more safe in terms of integrity.

2.Less chance to forget to update the derived fields.

*I am really confused some how but the requirement of the application forces us not to use three things that will load the SQL CPU load.

A:Triggers

B.UNIONS,Exits

C.Joins

|||

I fail to see how most of what you've listed as "advantages" are advantages. I would say:

Advantages:
1. No implicit transactions (All SQL Statements are an implied transaction, you haven't eliminated them, just simplified it -- But that's an advantage still)
2. Easy to debug -- For your application, if it's the only one accessing the data, yes.
3. Faster than triggers -- I doubt it. Sounds like you are going to have to make an extra round trip between the server and client to pull back the name field that you want to put in the field, which will make it many times slower, but holding locks for slightly less time. Unless you are caching the table(s) the 10 joins are getting their names from, in which case, you need to add the added application/web server memory cost as a disadvantage as well.
4. No unneccessary updates.
5. Could write code to maintain and check the alldata. -- This is not an advantage. It's a solution to the problem caused by the derived fields. It should be listed under disadvantages as "Have to write code to maintain and check the alldata".

Disadvantages:
1. Less safe in terms of integrity than triggers.
2. Possible data out of sync.
3. Increased application code, and extra logic that must be placed into every application that might need to update the data (or each routine within your application).
4. Have to write code to periodically maintain and check database integrity.

--

Please look into the indexed views I mentioned earlier, which doesn't suffer from the integrity issues, doesn't require more application logic (Other than you select from one view, and update a base table, but you're doing that from stored procedures now anyhow, right?) If the indexed views don't work for you, you could also use a BEFORE UPDATE/INSERT trigger, which aren't the nicest thing in the world to write, but keeps many of your listed advantages, and eliminates the disadvantages. (Guaranteed database integrity + no unneccessary updates + smaller lock time + faster than a client-side lookup)

As for your confusion on what you shouldn't use... (Triggers, UNIONS, Exits (did you mean EXISTS?), and joins)... Sounds like you've gotten information from someone who fell in love with a dumb record manager from the 1980's (Paradox, BTrieve, ISAM, or MySQL -- granted the latter is evolving beyond it's dumb record manager roots).

|||

I agree with Motley, because there is a reason the Object world have not created a replacement for Peter Chen 1976, the math that gave us what is now DRI(declarative referential integrity). I think you will run into data integrity problems as your application grow.

But the last part of your post is ok except JOINS because INNER JOINS with the AND operator will not eat up your CPU if you use management studio to show you execution cost and use the Profiler to optimize the cost of your SQL statement.

|||

indexed views > I would Love to use them butif I am not mistaken they have lots of rules to follow and I got to buy the enterprise editon and the 4 CPU price of SQL is4 X 20.000$where the standart edition is 4 X 6.000 USD for web applications.

for now I 'll be taking the risk of replication data inorder to have performance.

*I prefered to have a normalized and a clean data model where I can reuse the data logic without dublicating it.Pratically I could not find a way out for that in the physical design.

**Faster than triggers --> I might use threads.(which might mean more trouble but...)

|||

You are mistaken. They work in standard edition (Even SQL Express/MSDE), however, you must name the view directly. In enterprise edition if you have an indexed view, and a select/update doesn't mention the view, but it would benefit from it, it will automatically use it.

However, you are correct, there are some limitations, one of which is no LEFT JOINS, and no UNION. Just do them later (In another view that bases itself off the indexed view and left joins/unions with other data).

The nice part is, you can build it, test it, and see if it'll fit your needs in a matter of minutes.

How to build my SQL querry.

Hi.
I know this querry:

"SELECT TOP 10 * FROM MyTable ORDERBY ..."

will give the top 10 rows.

But how can I build a querry that can get the rows from 40-50 (ie).
Thanks.Try below code, it could helps you!

select top 10 * from (Select distinct top 50 * From TBLNAME order by Fieldname desc) a order by Fieldname asc|||This is a good example

http://www.4guysfromrolla.com/webtech/062899-1.shtml

Sunday, February 19, 2012

How to build an expression for a textbox?

Can I build an expression on a textbox with a "Sql Select" statement based
on the dataset? There is a parameter user selected on the dropdown and it
generates a dataset from the store procedure. This parameter is used on a
subquery for this dataset in the store procedure and it will return with the
records containing other parameter IDs. However I need to assign a record on
a textbox and require to filter out the record with the same parameterID
user selected in the dropdown. Thanks.
Eg. Parameters!Person.Value=2 selected in the dropdown
Recordset: SearchName
PersonID LName FName
1 Doe John
2 Doe Peter
3 Doe Jane
I need to assign the the name Doe, Peter on a textbox.If I understand correctly, you just want to use the data from the result set
that is returned from the data set.
If you go to the text box where you want to add the expression, right-click
that box, and click on the 'Expression' option.
In the Expression builder you can click the expansion (+) button next to
Fields, then select the Last Name, and click the insert button. Then in the
expression box, type a string that would add a comma, then finish by adding
the first name field to the expression box.
The result in the Expression box would look something like:
=Fields!LName.Value + ", " + Fields!FName.Value
Give that a try and see what happens.
"Paul" wrote:
> Can I build an expression on a textbox with a "Sql Select" statement based
> on the dataset? There is a parameter user selected on the dropdown and it
> generates a dataset from the store procedure. This parameter is used on a
> subquery for this dataset in the store procedure and it will return with the
> records containing other parameter IDs. However I need to assign a record on
> a textbox and require to filter out the record with the same parameterID
> user selected in the dropdown. Thanks.
> Eg. Parameters!Person.Value=2 selected in the dropdown
> Recordset: SearchName
> PersonID LName FName
> 1 Doe John
> 2 Doe Peter
> 3 Doe Jane
> I need to assign the the name Doe, Peter on a textbox.
>
>

How to browse INFORMATION_SCHEMA in Enterprise Manager

Dear all,
I try to (select * from information_schema.columns). It
works ok in query analyzer. But how can I access the information_schema
tables in Enterprise Manager? I try to browse all database, but I
cannot located where is information_schema located in? i.e. Which
database the information_schema is located in that I can browse in
Enterprise Manager?
ThanksI assume you are on 2000? These views only physically exists in the master d
atabase, so unless it is
master you want to look at, EM won't work. Use Query Analyzer and type your
queries instead.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"hon123456" <peterhon321@.yahoo.com.hk> wrote in message
news:1145342246.110319.286500@.u72g2000cwu.googlegroups.com...
> Dear all,
> I try to (select * from information_schema.columns). It
> works ok in query analyzer. But how can I access the information_schema
> tables in Enterprise Manager? I try to browse all database, but I
> cannot located where is information_schema located in? i.e. Which
> database the information_schema is located in that I can browse in
> Enterprise Manager?
> Thanks
>

How to browse for folder on SQL Server's machine?

Hi!
I know there is xp_dirtree, xp_subdirs, xp_fixeddrives procedures which
allows me to write a folder select dialog. But i have seen such dialog
somewhere in one of installers. Unfortunately I dont remember in what
installer.
I dont want to reinvent a wheel. So my question is: may be there is method
somewhere in SQL Server or in SQL-DMO or in DTS which implements a folder
selection dialog based on these stored procedures?T-SQL, DMO and DTS do not present the user with GUI objects. They provide
information, and your application must present that information is a dailog.
"Igor Solodovnikov" <IgorSolodovnikov@.discussions.microsoft.com> wrote in
message news:op.suvw7dy0n8ihmu@.iw2k.helpmicro.local...
> Hi!
> I know there is xp_dirtree, xp_subdirs, xp_fixeddrives procedures which
> allows me to write a folder select dialog. But i have seen such dialog
> somewhere in one of installers. Unfortunately I dont remember in what
> installer.
> I dont want to reinvent a wheel. So my question is: may be there is method
> somewhere in SQL Server or in SQL-DMO or in DTS which implements a folder
> selection dialog based on these stored procedures?|||Ok, thank you for information. I must ask my question another way: Do you
know any library implementing such a dialog?

> T-SQL, DMO and DTS do not present the user with GUI objects. They provide
> information, and your application must present that information is a
> dailog.
> "Igor Solodovnikov" <IgorSolodovnikov@.discussions.microsoft.com> wrote in
> message news:op.suvw7dy0n8ihmu@.iw2k.helpmicro.local...
>|||You have several options depending on what application development tool you
are using. This perhaps more a C# or Visual Basic question than SQL Server.
There is the Win32 API call SHBrowseForFolder
http://support.microsoft.com/defaul...kb;en-us;179497
How to write a managed C# wrapper for the API dialog call:
http://support.microsoft.com/defaul...kb;en-us;306285
Here is a Visual Basic sample:
http://www.vbexplorer.com/VBExplore...file_dialog.asp
I also think there is a method of the File System Object called
GetFolderName
http://msdn.microsoft.com/library/d...objectmodel.asp
"Igor Solodovnikov" <IgorSolodovnikov@.discussions.microsoft.com> wrote in
message news:op.suv0e6u4n8ihmu@.iw2k.helpmicro.local...
> Ok, thank you for information. I must ask my question another way: Do you
> know any library implementing such a dialog?
>
>|||As I mentioned in my original posting I can implement such dialog using
xp_dirtree, xp_subdirs, xp_fixeddrives procedures. But SQL Server's
Enterprise Manager already has such dialog. For example if you open
"Attach Database" dialog and then press browse [...] button Enterprise
Manager will show you "Browse For Existing File" dialog. And as you can
see all the path information in that dialog is local to SQL Server's
machine. This is what SHBrowseForFolder cannot do for you because
SHBrowseForFolder always shows paths relative to local machine.
My question is: Is there any way to reuse that Enterprise Manager's
"Browse For Existing File" dialog? Or I am obliged to reinvent it?
On Tue, 02 Aug 2005 19:30:46 +0300, JT <someone@.microsoft.com> wrote:

> You have several options depending on what application development tool
> you
> are using. This perhaps more a C# or Visual Basic question than SQL
> Server.
> There is the Win32 API call SHBrowseForFolder
> http://support.microsoft.com/defaul...kb;en-us;179497
> How to write a managed C# wrapper for the API dialog call:
> http://support.microsoft.com/defaul...kb;en-us;306285
> Here is a Visual Basic sample:
> http://www.vbexplorer.com/VBExplore...file_dialog.asp
> I also think there is a method of the File System Object called
> GetFolderName
> http://msdn.microsoft.com/library/d...objectmodel.asp
>
> "Igor Solodovnikov" <IgorSolodovnikov@.discussions.microsoft.com> wrote in
> message news:op.suv0e6u4n8ihmu@.iw2k.helpmicro.local...
>

How to bring out column names with bcp?

Hello, everyone:

I used bcp to generate a txt file as:

EXEC master..xp_cmdshell 'bcp "SELECT * FROM Test..Orders" queryout "c:/test.txt " -U tester -P tester -c'

It works fine except without column names of table. Does any one have idea that can bring out column names from table?

Thanks

ZYTColumn names is not one of the arguments of bcp.

You could do a "select * from <table> where 0=1" and save the output to a txt file, or script out the table schema and carry that across to the new location.|||Or you could use a union query with the column headings as literal strings in the row.|||Or you could use a union query with the column headings as literal strings in the row.I was going to suggest that. The main problem is that you then need to convert all data to character... which then means you need to be a little clever if you need to order your export for whatever reason.

http://weblogs.sqlteam.com/brettk/archive/2005/04/13/4395.aspx

I thought Mladen on SQLTeam had blogged something more sophisticated but I can't find it.|||I was going to suggest that. The main problem is that you then need to convert all data to character... which then means you need to be a little clever if you need to order your export for whatever reason.

http://weblogs.sqlteam.com/brettk/archive/2005/04/13/4395.aspx

I thought Mladen on SQLTeam had blogged something more sophisticated but I can't find it.

I am honored|||Lol - no offense. I mean I think he had some complicated automation code - I've never tried it. My own method, as it happens, is virtually identical to yours.|||Never [played with it, but my guess is you could use com automation..good luck|||This the way I export my "headers" in specific situation but you can modify it so it works for you as well.

DECLARE @.tmp varchar(1000), @.fld_list varchar(8000), @.loop int, @.i int, @.select varchar(2000), @.val_list varchar(8000)

............... YOUR CODE HERE ................

SET @.i=(SELECT COUNT(*)
FROM information_schema.columns
WHERE TABLE_NAME='ut_RptQryProdTemp')

SET @.loop = 1
SET @.fld_list = ''
SET @.val_list = ''
WHILE (@.loop <= @.i)
BEGIN
SELECT @.select = 'SELECT ''['' + COLUMN_NAME + ' + '''],''' + ' AS F
INTO ##fld_list
FROM information_schema.columns
WHERE TABLE_NAME=''ut_RptQryProdTemp'' AND ORDINAL_POSITION=' + convert(varchar(3),@.loop)
EXEC (@.select)
SELECT @.tmp = (SELECT REPLACE(F, ',', '') + ' AS ' + REPLACE(F, 'PRODOUT],', '],') + '' FROM ##fld_list)
SELECT @.val_list = @.val_list + @.tmp
SELECT @.fld_list = @.fld_list + REPLACE(STUFF(@.tmp, 1, 0, 'CAST('), ' AS [', ' AS varchar) AS [')
DROP TABLE ##fld_list
SET @.loop = @.loop + 1
END
SET @.fld_list = LEFT(@.fld_list, LEN(@.fld_list) - 1)
SET @.val_list = LEFT(@.val_list, LEN(@.val_list) - 1)
SET @.val_list = REPLACE(@.val_list, ',[', ',''')
SET @.val_list = REPLACE(@.val_list, '] AS', ''' AS')
SET @.val_list = REPLACE(@.val_list, 'PRODOUT', '')
SET @.val_list = STUFF(@.val_list, 1, 1, '''')

EXEC ('SELECT ' + @.val_list + ' UNION ALL SELECT ' + @.fld_list + ' FROM ut_RptQryProdTemp ORDER BY _DEP, _FAM, _STYLE, _COLOR, [_SIZE]')

As I said this is for a very specific situation, but if you're good with sql syntax you should be able to modify it.

good luck!|||Never [played with it, but my guess is you could use com automation..good luck

Any docs on COM AUTOMATION please ?|||Hello, everyone:

Thanks for all replies.

UNION cannot be used in bcp statement as SELECT part. I tried and got error. Pootle got a great idea. I did it and worked. Creat a view with all varchar column. Insert column names as first row. Then insert data from table. bcp to txt from view. This query will run automatically. The txt file name is changed by date. No problem on file name in bcp.

ZYT