Showing posts with label t-sql. Show all posts
Showing posts with label t-sql. Show all posts

Tuesday, March 27, 2012

Creating a View with detailed informations

Hello,
I have a code for creating view in T-SQL. I want to ask you guys, i want to make this result set should grouped by DepoAdi column and StokKodu (this is an alias sure you can get it from code). Did i make it on group by line? My second problem is i want to add 2 columns to this query. This 2 column will calculate some values with SUM function and - operator. At CRM.Depolar.DepoBilgileri table i have a column named Miktar (this one stores int type datas) and i have a column named islemturu(this one stores 1 or 0). I want to calculate Miktar values which rows has islemturu column 0 and subtract them from which rows has islemturu column 1 value and this computing action must be based on Grouped columns.

DepoAdi | StokKodu | Miktar | IslemTuru
ABS SK101 5 0
ABS SK101 3 1
ABS SK102 4 0
ABS SK102 3 1

This is the table and i'm imaging view what i want now...

DepoAdi | StokKodu | Miktar
ABS SK101 2
ABS SK102 1

How can i add this resultset to my code..

Thanks for reading... Waiting your answers.. Happy coding...

CREATE VIEW [CRM.Depolar.DepoDurumlari]

AS

SELECT [CRM.Depolar.DepoBilgileri].DepoAdi,

[CRM.Objeler.TemelGruplar.TureyenGruplar].GrupKodu + [CRM.Objeler.ObjeKodlari].ObjeKodu AS StokKodu

FROM [CRM.Depolar.DepoBilgileri], [CRM.Objeler.TemelGruplar.TureyenGruplar], [CRM.Objeler.ObjeKodlari], [CRM.Depolar.DepoHareketleri]

WHERE [CRM.Depolar.DepoBilgileri].Id IN (SELECT DepoBilgileri

FROM [CRM.Depolar]

WHERE Id IN (SELECT Depo

FROM [CRM.Depolar.DepoHareketleri]))

AND [CRM.Objeler.TemelGruplar.TureyenGruplar].Id IN (SELECT ObjeGrubu

FROM [CRM.Objeler]

WHERE Id IN (SELECT Id

FROM [CRM.StokKartlar]

WHERE Id IN (SELECT StokKart

FROM [CRM.Depolar.DepoHareketleri])))

AND [CRM.Objeler.ObjeKodlari].Id IN (SELECT StokKodu

FROM [CRM.StokKartlar.KartBilgileri]

WHERE Id IN (SELECT KartBilgileri

FROM [CRM.StokKartlar]

WHERE Id IN (SELECT StokKart

FROM [CRM.Depolar.DepoHareketleri])))

GROUP BY [CRM.Depolar.DepoBilgileri].DepoAdi, [CRM.Objeler.TemelGruplar.TureyenGruplar].GrupKodu, [CRM.Objeler.ObjeKodlari].ObjeKodu

Select DepoAdi

, StokKodu

, (Giren - Cikan) As Miktar

From

(

Select Depo.DepoAdi

, Depo.StokKodu

, Sum(Depo.Miktar) As Giren

, 0 As Cikan

From DepoBilgileri As Depo

Where IslemTuru = 0

Group By Depo.DepoAdi, Depo.StokKodu

Union All

Select Depo.DepoAdi

, Depo.StokKodu

, 0 As Giren

, Sum(Depo.Miktar) As Cikan

From DepoBilgileri As Depo

Where IslemTuru = 1

Group By Depo.DepoAdi, Depo.StokKodu

) As Core

|||

Thanks for your reply.. I solved problem with making some changes in my code.

CREATE VIEW [CRM.Depolar.DepoDurumlari]

AS

SELECT [CRM.Depolar.DepoBilgileri].DepoAdi,

[CRM.Objeler.TemelGruplar.TureyenGruplar].GrupKodu + [CRM.Objeler.ObjeKodlari].ObjeKodu AS StokKodu,

(SELECT SUM(CASE [CRM.Depolar.DepoHareketleri].IslemTuru

WHEN 0

THEN [CRM.Depolar.DepoHareketleri].Miktar

ELSE

-1 * [CRM.Depolar.DepoHareketleri].Miktar

END)

FROM [CRM.Depolar.DepoHareketleri]

GROUP BY [CRM.Depolar.DepoHareketleri].Depo, [CRM.Depolar.DepoHareketleri].StokKart) AS Miktar,

(SELECT SUM(CASE [CRM.Depolar.DepoHareketleri].IslemTuru

WHEN 0

THEN [CRM.Depolar.DepoHareketleri].Tutar

ELSE

-1 * [CRM.Depolar.DepoHareketleri].Tutar

END)

FROM [CRM.Depolar.DepoHareketleri]

GROUP BY [CRM.Depolar.DepoHareketleri].Depo, [CRM.Depolar.DepoHareketleri].StokKart) AS Tutar

FROM [CRM.Depolar.DepoBilgileri], [CRM.Objeler.TemelGruplar.TureyenGruplar], [CRM.Objeler.ObjeKodlari], [CRM.Depolar.DepoHareketleri]

WHERE [CRM.Depolar.DepoBilgileri].Id IN (SELECT [CRM.Depolar].DepoBilgileri

FROM [CRM.Depolar]

WHERE [CRM.Depolar].Id IN (SELECT [CRM.Depolar.DepoHareketleri].Depo

FROM [CRM.Depolar.DepoHareketleri]))

AND [CRM.Objeler.TemelGruplar.TureyenGruplar].Id IN (SELECT [CRM.Objeler].ObjeGrubu

FROM [CRM.Objeler]

WHERE [CRM.Objeler].Id IN (SELECT [CRM.StokKartlar].Id

FROM [CRM.StokKartlar]

WHERE [CRM.StokKartar].Id IN (SELECT [CRM.Depolar.DepoHareketleri].StokKart

FROM [CRM.Depolar.DepoHareketleri]

GROUP BY [CRM.Depolar.DepoHareketleri].StokKart)))

AND [CRM.Objeler.ObjeKodlari].Id IN (SELECT [CRM.StokKartlar.KartBilgileri].StokKodu

FROM [CRM.StokKartlar.KartBilgileri]

WHERE [CRM.StokKartlar.KartBilgileri].Id IN (SELECT [CRM.StokKartlar].KartBilgileri

FROM [CRM.StokKartlar]

WHERE [CRM.StokKartlar].Id IN (SELECT [CRM.Depolar.DepoHareketleri].StokKart

FROM [CRM.Depolar.DepoHareketleri]

GROUP BY [CRM.Depolar.DepoHareketleri].StokKart)))

GROUP BY [CRM.Depolar.DepoBilgileri].DepoAdi, [CRM.Objeler.TemelGruplar.TureyenGruplar].GrupKodu, [CRM.Objeler.ObjeKodlari].ObjeKodu

Sunday, March 25, 2012

Creating a T-SQL Stored Procedure to Truncate and Shrink ALL Log Files

Hello -
I'm hoping some T-SQL expert could help me figure out the code
necessary to implement a stored procedure that will truncate and
shrink the log files when run.
Let me give you a little background first. We are a small company
with an adequate, but not overwhelming amount of disk space. But,
with running SQL Server 2000 we do like the Recovery model set to
Full. Each week on back to back evenings (and on separate tapes) we
do a full backup with incremental backups throughout the week. After
the 1st full backup, I would like to run a procedure that would look
at each database and then truncate & shrink the log file. Then for
the 2nd full backup, I'd have much smaller logs obviously with the
ability to recover back to my original(s) via my 1st backup.
The code that works on individual databases that I now run manually
and change the parameters (@.database) accordingly is:
use master
BEGIN
BACKUP LOG @.database WITH TRUNCATE_ONLY
GO
USE @.database
DBCC SHRINKFILE (@.database + '_log')
I would like to have this placed in a stored procedure that would go
through each user database automatically. Unfortunately, I am not at
all familiar with the nuances of automatically changing databases nor
with working with stored procedures.
If anyone would/could be so kind as to provide me with the script that
would allow this to work as desired, I would be very very
appreciative. Thanks in advance for any and all help!
RichScull,
I am a little confused as to what your actually doing. You say you do a
FULL backup and then incremental but do not specify log backups at all other
than the truncate only. If you don't actually do log backups why do you
want to be in FULL recovery mode? What good does shrinking the logs do
anyway? When you backup a log (or a database) the size of the backup file
is proportional to the amount of data in the file not the size of the file
itself. So shrinking a log file will not give smaller backups. Shrinking
it and of itself is a dangerous act anyway for the reasons you mention. If
you have limited space and you shrink the file, which will certainly grow
back again, what will happen when you need more space and don't have it? It
is better to allocate the space in need (now and in the future) up front and
don't ever shrink the files. That way you ensure you always have the room
when you need it. If I misinterpreted what your doing please let me know so
we can work thru this.
Andrew J. Kelly
SQL Server MVP
"Scull" <myscullyfamily@.yahoo.com> wrote in message
news:a8a65e57.0402120523.459e3dea@.posting.google.com...
> Hello -
> I'm hoping some T-SQL expert could help me figure out the code
> necessary to implement a stored procedure that will truncate and
> shrink the log files when run.
> Let me give you a little background first. We are a small company
> with an adequate, but not overwhelming amount of disk space. But,
> with running SQL Server 2000 we do like the Recovery model set to
> Full. Each week on back to back evenings (and on separate tapes) we
> do a full backup with incremental backups throughout the week. After
> the 1st full backup, I would like to run a procedure that would look
> at each database and then truncate & shrink the log file. Then for
> the 2nd full backup, I'd have much smaller logs obviously with the
> ability to recover back to my original(s) via my 1st backup.
> The code that works on individual databases that I now run manually
> and change the parameters (@.database) accordingly is:
>
> use master
> BEGIN
> BACKUP LOG @.database WITH TRUNCATE_ONLY
> GO
> USE @.database
> DBCC SHRINKFILE (@.database + '_log')
> I would like to have this placed in a stored procedure that would go
> through each user database automatically. Unfortunately, I am not at
> all familiar with the nuances of automatically changing databases nor
> with working with stored procedures.
> If anyone would/could be so kind as to provide me with the script that
> would allow this to work as desired, I would be very very
> appreciative. Thanks in advance for any and all help!
> Rich|||Scull
Perhaps you want to use WITH INIT (after full backup database) to ovewrite
the log file.
Also,look at INFORMATION_SCHEMA.SCHEMATA in BOL.
"Scull" <myscullyfamily@.yahoo.com> wrote in message
news:a8a65e57.0402120523.459e3dea@.posting.google.com...
> Hello -
> I'm hoping some T-SQL expert could help me figure out the code
> necessary to implement a stored procedure that will truncate and
> shrink the log files when run.
> Let me give you a little background first. We are a small company
> with an adequate, but not overwhelming amount of disk space. But,
> with running SQL Server 2000 we do like the Recovery model set to
> Full. Each week on back to back evenings (and on separate tapes) we
> do a full backup with incremental backups throughout the week. After
> the 1st full backup, I would like to run a procedure that would look
> at each database and then truncate & shrink the log file. Then for
> the 2nd full backup, I'd have much smaller logs obviously with the
> ability to recover back to my original(s) via my 1st backup.
> The code that works on individual databases that I now run manually
> and change the parameters (@.database) accordingly is:
>
> use master
> BEGIN
> BACKUP LOG @.database WITH TRUNCATE_ONLY
> GO
> USE @.database
> DBCC SHRINKFILE (@.database + '_log')
> I would like to have this placed in a stored procedure that would go
> through each user database automatically. Unfortunately, I am not at
> all familiar with the nuances of automatically changing databases nor
> with working with stored procedures.
> If anyone would/could be so kind as to provide me with the script that
> would allow this to work as desired, I would be very very
> appreciative. Thanks in advance for any and all help!
> Rich|||First off, I want to thank you for your input- it's geratly appreciated!
I'm sorry I wasn't clear in terms of how we perform our backups. We use
a separate backup application for backing up all the SQL Server
databases and their respective transaction logs. We do FULL backups on
Friday and Saturday evening, and incremental backups throughout the
week.
My space issues arose when I converted all of my 7.0 databases to 2000
about 4 months ago. Rather quickly after converting the db's, I noticed
we were running out of disk space. In reviewing one of the converted
databases that was affecting my disk space - I noticed the MDF file with
a size of about 1 GIG and the transaction log with a size of 17 GIG.
Obviously, I was like "Yikes."
Anyway, at this point in time I'd would rather keep the recovery mode
set to full so that we could perform point-in-time recoveries. I figure
the best way, given my disk space concerns, for me to insure possible
point-in-time recovery is to take advantage of the fact that 2 full
backups are done each week. If after the 1st full backup, I can
truncate and shrink the transaction log before the 2nd full backup - I
will have a choice of restore points in the event something should go
awry.
Now while I know this is not necessarily the optimal solution, I do not
know of a better one at this point. I am obviously wide open to
suggestions/recommendations.
If no strategic process changes can be realized, I think I need to find
the answer to my T-SQL question concerning establishing a stored
procedure that I can schedule after the Friday backup but before the
Saturday backup - that will truncate and shrink the transaction log(s)
for each of the user databases automatically.
I will also check out the WITH INIT, etc. in the BOL.
Thanks in advance for any more feedback.
Rich
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!|||Rich,
Your solution is to issue regular Log backups and forget about truncating
and shrinking the logs. If you want point in time recovery you have to be
in FULL mode. If your in FULL mode the log file will keep growing and
growing since it needs a log backup to properly backup the committed trans
and truncate them. If you don't issue log backups what will happen if your
disk array dies and you must restore from scratch? You will only have up to
your last full and incremental backup. You have lost your ability to
restore up to the minute or point in time. If you issue regular log backups
your tran log itself will stay at a size that it needs over a point it time
and should never be shrunk once it reaches that quiescent state. Of coarse
you log backup files will now contain the data that used to be in your log
so you need a place to store those and hopefully it's not on the same array
as the db. That should solve your disk space issue and alleviate the need
to schedule a log truncation and shrinking. Just schedule regular log
backups. The interval is up to you. Every 15 minutes or 1/2 hour should
keep your log file from growing too much and keep you relatively safe as
well. If your concerned about room to place your backup files you might
consider using a product called SQL LiteSpeed. It will reduce the time for
a backup and give you much smaller files to boot.
Andrew J. Kelly
SQL Server MVP
"Rich S" <myscullyfamily@.yahoo.com> wrote in message
news:O1Kiq8d8DHA.3112@.tk2msftngp13.phx.gbl...
> First off, I want to thank you for your input- it's geratly appreciated!
> I'm sorry I wasn't clear in terms of how we perform our backups. We use
> a separate backup application for backing up all the SQL Server
> databases and their respective transaction logs. We do FULL backups on
> Friday and Saturday evening, and incremental backups throughout the
> week.
> My space issues arose when I converted all of my 7.0 databases to 2000
> about 4 months ago. Rather quickly after converting the db's, I noticed
> we were running out of disk space. In reviewing one of the converted
> databases that was affecting my disk space - I noticed the MDF file with
> a size of about 1 GIG and the transaction log with a size of 17 GIG.
> Obviously, I was like "Yikes."
> Anyway, at this point in time I'd would rather keep the recovery mode
> set to full so that we could perform point-in-time recoveries. I figure
> the best way, given my disk space concerns, for me to insure possible
> point-in-time recovery is to take advantage of the fact that 2 full
> backups are done each week. If after the 1st full backup, I can
> truncate and shrink the transaction log before the 2nd full backup - I
> will have a choice of restore points in the event something should go
> awry.
> Now while I know this is not necessarily the optimal solution, I do not
> know of a better one at this point. I am obviously wide open to
> suggestions/recommendations.
> If no strategic process changes can be realized, I think I need to find
> the answer to my T-SQL question concerning establishing a stored
> procedure that I can schedule after the Friday backup but before the
> Saturday backup - that will truncate and shrink the transaction log(s)
> for each of the user databases automatically.
> I will also check out the WITH INIT, etc. in the BOL.
> Thanks in advance for any more feedback.
> Rich
> *** Sent via Developersdex http://www.examnotes.net ***
> Don't just participate in USENET...get rewarded for it!|||Rich
I suggest you setup a SQL 2000 Agent Job executing the following TSQL
command:
DBCC SHRINKFILE(2, TRUNCATEONLY)
on the DB(s) in question. Set it to run off hours, the "2" should be
for the
Log(LDF) file, a "1" should be the for MDF file.
I'm still waiting myself to see a script that will parse thru the DBs
on a server and build the DBCC above for every DB.
good luck
Steven|||You could do it vb6 or .net using
Public oSQLServer As New SQLDMO.SQLServer
For Each oDatabase In oSQLServer.Databases
'If odatabase.Status <> SQLOLEDBStat_Inaccessible Then
form1.List_Databases.AddItem oDatabase.Name
'frmExecVB.lstCat.AddItem oDatabase.Name
'End If
Next oDatabase
Then you can build up a string using filesystem object to write your
script for you.
Have a look at SQLDMO Object, it rocks !
I've even got some code to look round your network and come back with a
list of sql servers...
Tim Heap
Software & Database Manager
POSTAR Ltd
www.postar.co.uk
tim@.postar.co.uk
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!|||Thanks for your reply. I have still been working on a solution and have
not had the opportunity to write back. I work for a relatively small
company where I were a number of 'hats' of which being the DBA is just
one of them.
Anyway, I setup transaction log backups hourly throughout the day (I
don't have that many transactions - but do have a lot of databases) and
that is working fine. In tracking the transaction log size, I was able
to summize that it grew immensely on late Saturday evenings - which is
the time I kick off my database maintenance plan which includes
rebuilding indexes and optimizing the databases.
For example, one particular database who MDF is 540 mb and had a
transaction log of 52 mb throughout the week - had it's transaction log
grow to 468 mb after running the maintenance plan.
I am thinking that I should then 1) backup the transaction log with
truncate only, then 2) run the SHRINKFILE command to reduce the
transaction log to say... 50 mb. 3) Then backup the entire database.
If that works, I would need to incorporate that into all of my db plans.
Any thoughts/concerns? Thanks again for everyone's assitance!!!
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!|||try the following to truncate TLogs:
--drop procedure xxx_SQL_Logspace_truncate_all
--CREATE procedure xxx_SQL_Logspace_truncate_all as
USE Master
DECLARE @.logname varchar(20)
DECLARE @.query varchar(255)
DECLARE LogList_cursor CURSOR FOR
SELECT name FROM master.dbo.sysdatabases
ORDER BY name
OPEN LogList_cursor
FETCH NEXT FROM LogList_cursor INTO @.logname
WHILE @.@.FETCH_STATUS = 0
BEGIN
-- add DB's you want to skip to the following list
IF RTRIM(@.logname) = "master" or
RTRIM(@.logname) = "model" or
RTRIM(@.logname) = "msdb" or
RTRIM(@.logname) = "pubs" or
RTRIM(@.logname) = "Northwind"
print @.logname + ' skipped'
ELSE
begin
Set @.query = "DBCC SHRINKFILE("+ RTRIM(@.logname) + ".LDF, TRUNCATEONLY)"
select @.query
end
FETCH NEXT FROM LogList_cursor into @.logname
END
-- following will list all DB's Logspace stats
DBCC SQLPERF(LOGSPACE)
CLOSE LogList_cursor
DEALLOCATE LogList_cursor
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

Creating a T-SQL Stored Procedure to Truncate and Shrink ALL Log Files

Hello -
I'm hoping some T-SQL expert could help me figure out the code
necessary to implement a stored procedure that will truncate and
shrink the log files when run.
Let me give you a little background first. We are a small company
with an adequate, but not overwhelming amount of disk space. But,
with running SQL Server 2000 we do like the Recovery model set to
Full. Each week on back to back evenings (and on separate tapes) we
do a full backup with incremental backups throughout the week. After
the 1st full backup, I would like to run a procedure that would look
at each database and then truncate & shrink the log file. Then for
the 2nd full backup, I'd have much smaller logs obviously with the
ability to recover back to my original(s) via my 1st backup.
The code that works on individual databases that I now run manually
and change the parameters (@.database) accordingly is:
use master
BEGIN
BACKUP LOG @.database WITH TRUNCATE_ONLY
GO
USE @.database
DBCC SHRINKFILE (@.database + '_log')
I would like to have this placed in a stored procedure that would go
through each user database automatically. Unfortunately, I am not at
all familiar with the nuances of automatically changing databases nor
with working with stored procedures.
If anyone would/could be so kind as to provide me with the script that
would allow this to work as desired, I would be very very
appreciative. Thanks in advance for any and all help!
RichScull,
I am a little confused as to what your actually doing. You say you do a
FULL backup and then incremental but do not specify log backups at all other
than the truncate only. If you don't actually do log backups why do you
want to be in FULL recovery mode? What good does shrinking the logs do
anyway? When you backup a log (or a database) the size of the backup file
is proportional to the amount of data in the file not the size of the file
itself. So shrinking a log file will not give smaller backups. Shrinking
it and of itself is a dangerous act anyway for the reasons you mention. If
you have limited space and you shrink the file, which will certainly grow
back again, what will happen when you need more space and don't have it? It
is better to allocate the space in need (now and in the future) up front and
don't ever shrink the files. That way you ensure you always have the room
when you need it. If I misinterpreted what your doing please let me know so
we can work thru this.
--
Andrew J. Kelly
SQL Server MVP
"Scull" <myscullyfamily@.yahoo.com> wrote in message
news:a8a65e57.0402120523.459e3dea@.posting.google.com...
> Hello -
> I'm hoping some T-SQL expert could help me figure out the code
> necessary to implement a stored procedure that will truncate and
> shrink the log files when run.
> Let me give you a little background first. We are a small company
> with an adequate, but not overwhelming amount of disk space. But,
> with running SQL Server 2000 we do like the Recovery model set to
> Full. Each week on back to back evenings (and on separate tapes) we
> do a full backup with incremental backups throughout the week. After
> the 1st full backup, I would like to run a procedure that would look
> at each database and then truncate & shrink the log file. Then for
> the 2nd full backup, I'd have much smaller logs obviously with the
> ability to recover back to my original(s) via my 1st backup.
> The code that works on individual databases that I now run manually
> and change the parameters (@.database) accordingly is:
>
> use master
> BEGIN
> BACKUP LOG @.database WITH TRUNCATE_ONLY
> GO
> USE @.database
> DBCC SHRINKFILE (@.database + '_log')
> I would like to have this placed in a stored procedure that would go
> through each user database automatically. Unfortunately, I am not at
> all familiar with the nuances of automatically changing databases nor
> with working with stored procedures.
> If anyone would/could be so kind as to provide me with the script that
> would allow this to work as desired, I would be very very
> appreciative. Thanks in advance for any and all help!
> Rich|||Scull
Perhaps you want to use WITH INIT (after full backup database) to ovewrite
the log file.
Also,look at INFORMATION_SCHEMA.SCHEMATA in BOL.
"Scull" <myscullyfamily@.yahoo.com> wrote in message
news:a8a65e57.0402120523.459e3dea@.posting.google.com...
> Hello -
> I'm hoping some T-SQL expert could help me figure out the code
> necessary to implement a stored procedure that will truncate and
> shrink the log files when run.
> Let me give you a little background first. We are a small company
> with an adequate, but not overwhelming amount of disk space. But,
> with running SQL Server 2000 we do like the Recovery model set to
> Full. Each week on back to back evenings (and on separate tapes) we
> do a full backup with incremental backups throughout the week. After
> the 1st full backup, I would like to run a procedure that would look
> at each database and then truncate & shrink the log file. Then for
> the 2nd full backup, I'd have much smaller logs obviously with the
> ability to recover back to my original(s) via my 1st backup.
> The code that works on individual databases that I now run manually
> and change the parameters (@.database) accordingly is:
>
> use master
> BEGIN
> BACKUP LOG @.database WITH TRUNCATE_ONLY
> GO
> USE @.database
> DBCC SHRINKFILE (@.database + '_log')
> I would like to have this placed in a stored procedure that would go
> through each user database automatically. Unfortunately, I am not at
> all familiar with the nuances of automatically changing databases nor
> with working with stored procedures.
> If anyone would/could be so kind as to provide me with the script that
> would allow this to work as desired, I would be very very
> appreciative. Thanks in advance for any and all help!
> Rich|||Rich
I suggest you setup a SQL 2000 Agent Job executing the following TSQL
command:
DBCC SHRINKFILE(2, TRUNCATEONLY)
on the DB(s) in question. Set it to run off hours, the "2" should be
for the
Log(LDF) file, a "1" should be the for MDF file.
I'm still waiting myself to see a script that will parse thru the DBs
on a server and build the DBCC above for every DB.
good luck
Steven

Wednesday, March 21, 2012

Creating a simple update trigger

I am extremely new at SQL Server2000 and t-sql and I'm looking to
create a simple trigger. For explanation sake, let's say I have 3
columns in one table ... Col_1, Col_2 and Col_3. The data type for
Col_1 and Col_2 are bit and Col_3 is char. I want to set a trigger on
Col_2 to compare Col_1 to Col_2 when Col_2 is updated and if they're
the same, set the value on Col_3 to "Completed". Can someone please
help me?

Thanks,
JustinHi

Posting DDL (Create table statements etc.) and example data (as Insert
statements) removes any ambiguity. Within the trigger try something like:

UPDATE t
SET Col_3 = "Completed"
FROM MyTable t JOIN INSERTED i on i.pkcol = t.pkcol
JOIN DELETED d on d.pkcol = t.pkcol
WHERE i.col2 <> d.col2
AND i.col2 = i.col1

John

"Justin" <jhosman@.numc.edu> wrote in message
news:450900ad.0407151958.73494eeb@.posting.google.c om...
> I am extremely new at SQL Server2000 and t-sql and I'm looking to
> create a simple trigger. For explanation sake, let's say I have 3
> columns in one table ... Col_1, Col_2 and Col_3. The data type for
> Col_1 and Col_2 are bit and Col_3 is char. I want to set a trigger on
> Col_2 to compare Col_1 to Col_2 when Col_2 is updated and if they're
> the same, set the value on Col_3 to "Completed". Can someone please
> help me?
> Thanks,
> Justin|||If col_3 is always based on the value of columns 1 and 2 then you don't need
it and you don't need the trigger either. Drop col_3 and calculate the
"completed" status in a view or when you query the table. Columns based on
other (non-key) columns are called Transitive Dependencies and avoiding them
is one of the goals of correct database design.

--
David Portas
SQL Server MVP
--|||David,

You're right, of course but I was just giving an example. What I
actually have is 19 columns. 18 of them are bit value 1 of them char.
The 18 represent 9 pairs. Each pair represents requested and created.
I wanted to write an update trigger on all 9 created fields that would
check to see if ALL of the requested fields were equal to thier
respective created fields and if they were, to Change the status of
field 19 from active to completed.

This is for a new user account form whereby a user would request access
to certain systems (administrated in diffrent areas) and the request
status would stay in an active state until all of the accounts were
completed by the various administrators. That way every time one
administrator created their respective account the database would check
and possible change the status of the request.

If you have any insight in this area it would be much appreciated. I
certainly need all of the help I can get.

Thanks,

Justin

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Hi John,

Thanks for your help I really appreciate it. I tried your code and I
keep getting "invalid column name" error messages. Here is my attempt
at the code...

CREATE TRIGGER CHECKSTATUS
ON dbo.useraccounttbl
FOR UPDATE AS
IF UPDATE (internetcreated)
BEGIN
UPDATE t
SET completedstatus = "Completed"
FROM useraccounttbl t join INSERTED i on i.pkcol = t.pkcol
JOIN DELETED d on d.pkcol = t.pkcol
WHERE i.internetcreated <> d.internetccreated
AND i.internetcreated = i.internetrequested
END

I'm tring to test this on these 3 columns what I will need to do on 16
more. I explained it to another person who reponded like this...

What I actually have is 19 columns. 18 of them are bit value 1 of them
char. The 18 represent 9 pairs. Each pair represents requested and
created. I wanted to write an update trigger on all 9 created fields
that would check to see if ALL of the requested fields were equal to
thier respective created fields and if they were, to Change the status
of field 19 from active to completed.

This is for a new user account form whereby a user would request access
to certain systems (administrated in diffrent areas) and the request
status would stay in an active state until all of the accounts were
created by the various administrators. That way every time one
administrator created their respective account the database would check
and possible change the status of the request.

Thanks again for all of your help.

Justin

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Hi

pkcol are the columns in the primary key, it could be more than one column
that uniquely defines each row. As there was/is no DDL it was used as short
hand.

You can pair each value

UPDATE t
SET completedstatus = "Completed"
FROM useraccounttbl t join INSERTED i on i.pkcol = t.pkcol
JOIN DELETED d on d.pkcol = t.pkcol
WHERE ( i.col1 <> d.col1
AND i.col1 = i.col2 )
OR ( i.col3 <> d.col3
AND i.col3 = i.col4 )
OR ( .......
)

John

"Justin Hosman" <hateface72@.yahoo.com> wrote in message
news:40f7dbfb$1$16414$c397aba@.news.newsgroups.ws.. .
> Hi John,
> Thanks for your help I really appreciate it. I tried your code and I
> keep getting "invalid column name" error messages. Here is my attempt
> at the code...
> CREATE TRIGGER CHECKSTATUS
> ON dbo.useraccounttbl
> FOR UPDATE AS
> IF UPDATE (internetcreated)
> BEGIN
> UPDATE t
> SET completedstatus = "Completed"
> FROM useraccounttbl t join INSERTED i on i.pkcol = t.pkcol
> JOIN DELETED d on d.pkcol = t.pkcol
> WHERE i.internetcreated <> d.internetccreated
> AND i.internetcreated = i.internetrequested
> END
> I'm tring to test this on these 3 columns what I will need to do on 16
> more. I explained it to another person who reponded like this...
> What I actually have is 19 columns. 18 of them are bit value 1 of them
> char. The 18 represent 9 pairs. Each pair represents requested and
> created. I wanted to write an update trigger on all 9 created fields
> that would check to see if ALL of the requested fields were equal to
> thier respective created fields and if they were, to Change the status
> of field 19 from active to completed.
> This is for a new user account form whereby a user would request access
> to certain systems (administrated in diffrent areas) and the request
> status would stay in an active state until all of the accounts were
> created by the various administrators. That way every time one
> administrator created their respective account the database would check
> and possible change the status of the request.
> Thanks again for all of your help.
> Justin
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!|||>> Here is my attempt at the code... <<

I am sure that someone will kludge something really ugly and complex
for you, but the real problem is that you are still an assembly level
programmer trying to move to an abstract high level language.

1) Stop putting that silly "-tbl" prefix on table names! This is
saying that your table models pieces of furniture that belong to user
accounts, according to ISO-11179. There is only one data structure in
SQL anyway. What you want is a name that tells us what set of
entities or relationship the table models; since it is a set,
something like "UserAccounts" is fine.

Volumns are not anything like Fields; until you know and think in
terms of rows and columns, you will never "get it" and will continue
to write BASIC in SQL.

2) SQL is a declarative language and probably the first such animal
you have ever seen. You tell it WHAT you want and it figures out HOW
to get it. This is a huge advance in programming. If the data
changes, the query stays the same but the execution plan changes with
you coding anything new.

>> What I actually have is 19 columns. 18 of them are bit value 1 of
them
char. The 18 represent 9 pairs. Each pair represents requested and
created. <<

ARRGH! Assembly language and punch card programming!! Think
relational, not physical. At best from this description, you have
nine attributes which ought to be in one column each; having "half an
atribute" is a design flaw called attribute splitting. At this point,
I have to guess at specs, but it looks like each attribute has two
values (requested and created). NEVER, NEVER, NEVER use BIT data (I
have an article due out soon in DBAzine with some of the many
reasons).

Sit down and design a status code with all the values you need; you
have
"requested" and "created", so nothing is needed for "failed" or
"rejected" in your situation?

The right way to do this is NOT with a trigger (procedural code!! The
HOW of the answer), but with a VIEW that will compute the status
(declarative code!! The WHAT of the answer).

>> This is for a new user account form whereby a user would request
access
to certain systems (administrated in diffrent areas) and the request
status would stay in an active state until all of the accounts were
created by the various administrators. <<

Now we have specs and can see that you don't know about First Normal
Form (1NF). The nine pairs are a repeating group in the data model.
Let us "flatten" out the table.

CREATE TABLE UserAccounts
(user_id INTEGER NOT NULL -- tables relate to each other, files don't
REFERENCES Personnel (user_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
admin_area INTEGER NOT NULL -- tables relate to each other, files
don't
REFERENCES Administration (admin_area)
ON DELETE CASCADE
ON UPDATE CASCADE,
request_status INTEGER DEFAULT 0 NOT NULL -- zero is "requested,not
granted"
CHECK (request_status IN (..)) -- columns have
constraints,fields don't
PRIMARY KEY (user_id, admin_area));

Your report:

CREATE VIEW RequestStatus (user_id, total_status)
AS
SELECT user_id, MIN(request_status)
FROM UserAccounts
GROUP BY user_id;

Add or drop admin areas as you wish; add more status codes easily; DRI
actions maintain the schema for you. The schema is a WHOLE, not a
collection of files that stand alone -- design the whole!|||Justin Hosman (hateface72@.yahoo.com) writes:
> Thanks for your help I really appreciate it. I tried your code and I
> keep getting "invalid column name" error messages. Here is my attempt
> at the code...
> CREATE TRIGGER CHECKSTATUS
> ON dbo.useraccounttbl
> FOR UPDATE AS
> IF UPDATE (internetcreated)
> BEGIN
> UPDATE t
> SET completedstatus = "Completed"
> FROM useraccounttbl t join INSERTED i on i.pkcol = t.pkcol
> JOIN DELETED d on d.pkcol = t.pkcol
> WHERE i.internetcreated <> d.internetccreated
> AND i.internetcreated = i.internetrequested
> END

"Completed" should be 'Completed'. SQL Server actually permits you
to use both " and ' to delimit strings, but " is only possible under
certain conditions, so stick with '.

> What I actually have is 19 columns. 18 of them are bit value 1 of them
> char. The 18 represent 9 pairs. Each pair represents requested and
> created. I wanted to write an update trigger on all 9 created fields
> that would check to see if ALL of the requested fields were equal to
> thier respective created fields and if they were, to Change the status
> of field 19 from active to completed.

A computed column would be easier:

CREATE TABLE blablabla
(pkcol ...
request1 bit NOT NULL,
completed1 bit NOT NULL,
..
status AS (CASE WHEN request1 = completed1 AND
request2 = completed2 AND
...
request9 = comepleted9 THEN 'Completed'
ELSE 'Pending'
END)

However, this is not a very good design. You should probaly change
all these columns to rows, so that if a tenth request is added, all
you need to add one more row to defining table:

CREATE TABLE requesttypes
(reqtype char(3) NOT NULL, -- mnemonic
reqname varchar(40) NOT NULL, -- descriptive
CONSTRIAINT PK_reqtypes PRIMARY KEY requesttypes (reqtype))

CREATE TABLE requests (
usrid int NOT NULL,
reqtype char(3) NOT NULL,
status char(1) NOT NULL
-- New or completed
CONSTRAINT ckc_req_status CHECK (status IN ('N', 'C')),
CONSTRAINT pk_reqs PRIMARY KEY (usrid, reqtype),
CONSTRAINT fk_regtype FOREIGN KEY (reqtype)
REFERENCES requesttypes( requtype),
CONSTRAINR fk_userd FOREIGN KEY (usrid)
REFERENCES users (usrid))

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Sunday, March 11, 2012

Creating a Package in SQL Server (T-SQL)

Hello,
Can we create a new Package in SQL Server (T-SQL). Oracle has the option of creating a new package using 'CREATE PACKAGE'.
Is SQL Server has anything similar to this.
Hi Aparna,
SQL Server doesn't have the concept of a package. You can
group stored procedures in SQL Server but it's nothing like
having a package, doesn't have the functionality of packages
(i.e. no package level variables to be used by other
procedures in the package) - it's really not the same thing
at all.
I don't know if have seen the following or not but there is
chapter in the SQL Server 2000 resource kit on migrating
Oracle databases to SQL Server. It has a lot of useful
information to help with such a migration. You can find it
online at:
Chapter 7 - Migrating Oracle Databases to SQL Server 2000
http://www.microsoft.com/resources/d...rt2/c0761.mspx
-Sue
On Wed, 31 Mar 2004 22:56:09 -0800, Aparna
<aparna.shirodkar@.lycos.com> wrote:

>Hello,
>Can we create a new Package in SQL Server (T-SQL). Oracle has the option of creating a new package using 'CREATE PACKAGE'.
>Is SQL Server has anything similar to this.
|||Hi Sue,
Thanx once again for the help. I will go thru the link u mentioned. Let's hope our problem gets resolved.
|||Hi Aparna
Good try, hope you are fine. Just flashing old memories. bye
Posted via DevelopmentNow.com Groups
http://www.developmentnow.com

Creating a Package in SQL Server (T-SQL)

Hello,
Can we create a new Package in SQL Server (T-SQL). Oracle has the option of
creating a new package using 'CREATE PACKAGE'.
Is SQL Server has anything similar to this.Hi Aparna,
SQL Server doesn't have the concept of a package. You can
group stored procedures in SQL Server but it's nothing like
having a package, doesn't have the functionality of packages
(i.e. no package level variables to be used by other
procedures in the package) - it's really not the same thing
at all.
I don't know if have seen the following or not but there is
chapter in the SQL Server 2000 resource kit on migrating
Oracle databases to SQL Server. It has a lot of useful
information to help with such a migration. You can find it
online at:
Chapter 7 - Migrating Oracle Databases to SQL Server 2000
http://www.microsoft.com/resources/...r />
0761.mspx
-Sue
On Wed, 31 Mar 2004 22:56:09 -0800, Aparna
<aparna.shirodkar@.lycos.com> wrote:

>Hello,
>Can we create a new Package in SQL Server (T-SQL). Oracle has the option of
creating a new package using 'CREATE PACKAGE'.
>Is SQL Server has anything similar to this.|||Hi Sue,
Thanx once again for the help. I will go thru the link u mentioned. Let's ho
pe our problem gets resolved.|||Hi Aparna
Good try, hope you are fine. Just flashing old memories. bye
Posted via DevelopmentNow.com Groups
http://www.developmentnow.com