SQL Server 2005 Query/trigger/function (whatever It Is That I Need)
Dec 8, 2006
Hey guys maybe you can help me out, been trying to figure this one out all day at work. I know how to use columns in a table to calculate another column in that same table. But I need to do some math on columns from a totally seperate table. Here is my scenario
table 1 = stock table
table 2 = Purchase order table
in table 2 there are line items that have ordered quantities for parts that we have ordered
in table 1 under each part number is a field for "quantity on order"
I need to compute the "quantity on order" in table 1 by summing all of the quantities in table 2 where the partnumber = the partnumber from table 1
quantity on order (table 1) = sum of all quantities (table 2) where the part numbers match
so for part number 516 i have this
table 2
poNumber partNumber quantity
1 516 1
2 516 12
3 516 4
table 1
partNumber inStock onOrder
516 0 17(this is what i am trying to figure out how to compute)
any help on this qould be appreciated. I would like the database to automatically do this itself if at all possible.
View 3 Replies
ADVERTISEMENT
Feb 5, 2008
I wrote a function and a SQL to get the 3 columns Date,Total Orders
& Amount, for dates between Date Started and Date Completed if I
pass different Dates in the SQL I get the correct result but if I pass
same dates then I don't get the result I am looking for .For Instance,if I give Date From=1/02/2008 ;Date To=1/8/2008(Different dates )I am getting values for all the three columns.But I give same dates for Date From=01/02/2008 ;Date To=01/02/2008 then I am not getting the records.Some how I could not trace what could be the error in my SQL /Function.I appreciate if I could get some work around for this.Thanks! Function:create function dbo.CreateDateList(@start datetime, @end datetime)returns @t table ( [date] datetime )asbegin if @start is null or @end is null return if @start > @end return set @start = convert(datetime, convert(varchar(10), @start, 120), 120) set @end = convert(datetime, convert(varchar(10), @end, 120), 120) while @start < @end begin insert into @t ( [date] ) values (@start) set @start = dateadd(day, 1, @start) end returnend ---------SELECT qUERY---------- SELECT Convert(Varchar(15), l.[date],101)as Date,COUNT(o.OrderID ) AS TotalOrders,ISNULL(Round(SUM(o.SubTotal),2),0) AS Amount , 1 as OrderByCol FROM dbo.CreateDateList(@DateFrom , @DateTo) l LEFT OUTER JOIN orders o ON o.Datecompleted >=Convert(Datetime, l.[date],101) and o.Datecompleted < dateadd(day,1,convert(Datetime, l.[date],101)) WHERE StoreID=@StoreID GROUP BY Convert(Varchar(15), l.[date],101) Union SELECT 'Grand Total' as Total,NULL AS TotalOrders, ISNULL(Round(SUM(o.SubTotal),2),0) AS Amount, 2 as OrderByCol FROM dbo.CreateDateList(@DateFrom , @DateTo) l LEFT OUTER JOIN orders o ON o.Datecompleted >=Convert(Datetime, l.[date],101) and o.Datecompleted < dateadd(day,1,convert(Datetime, l.[date],101)) WHERE StoreID=@StoreID Order by Date
View 6 Replies
View Related
Feb 4, 2008
Can anybody know ,how can we add builtin functions(ROW_NUMBER()) of Sql Server 2005 into database library.
I get this error when i used into storeprocedure :
ROW_NUMBER() function is not recognized in store procedure.
i used MS SQL SERVER 2005 , so i think "ROW_FUNCTION()" is not in MS SQL SERVER 2005 database library.
I need to add that function into MS SQL SERVER 2005 database library.
Can anbody know how we can add that function into MS SQL SERVER 2005 database library?
View 4 Replies
View Related
Aug 24, 2007
I have a trigger written below to update another table when one table is updated.
Basically it works when i update row after row from enterprise manager However when i use a script to update 10 or 20 rows then this trigger does not work. Can any one offer any suggestions on where this issue could be ?
DECLARE @iCount INT
DECLARE @OldValue VARCHAR(255)
DECLARE @NEWVALUE VARCHAR(255)
DECLARE @EQNAME VARCHAR(255)
DECLARE @EQTYPE VARCHAR(255)
DECLARE @TEST VARCHAR(255)
SET @NEWVALUE = 'INIT'
IF (UPDATE(VALUE))
BEGIN
SELECT @OldValue = deleted.value from deleted
SELECT @NEWVALUE = inserted.VALUE,@EQNAME = inserted.EQ_NAME FROM inserted where inserted.attr = 'AreaCfg'
IF (@@ROWCOUNT =0)
BEGIN
RETURN
END
IF ((@NEWVALUE = '') OR (@NEWVALUE is NULL))
BEGIN
DELETE [TABLE-1] WHERE ENTITYID = @EQNAME
RETURN
END
IF ((@NEWVALUE != @OldValue))
BEGIN
SELECT @iCount = Count(*) FROM [TABLE-1] WHERE ENTITYID = @EQNAME
IF (@iCount = 0)
BEGIN
-- No records are available so insert
SELECT @EQTYPE = Typ FROM IP_EQ WHERE EQ_NAME = @EQNAME
INSERT INTO [TABLE-1] (AlarmGroupId, EntityID, EntityType, OwnerId) VALUES (@NEWVALUE,@EQNAME,@EQTYPE,'Production Tracker')
END
IF (@iCount > 0)
BEGIN
-- No records are available so insert
SELECT @EQTYPE = Typ FROM IP_EQ WHERE EQ_NAME = @EQNAME
UPDATE [TABLE-1] SET ALARMGROUPID = @NEWVALUE WHERE ENTITYID = @EQNAME
END
END
END
View 3 Replies
View Related
Oct 16, 2006
I am trying to create this trigger
CREATE TRIGGER User_Insert ON aspnet_users AFTER UPDATE AS
IF UPDATE (UserId)
insert into users (aspnet_user_id, username)
select au.userid, au.username
from aspnet_users au
where au.userid != users.aspnet_user_id;
Whenever the aspnet_users table has a new user added I want the Userid and username fields from that table inserted into the
the aspnet_user_id and username fileds of the users table.
when creating the trigger I get the following error..
Msg 4104, Level 16, State 1, Procedure User_Insert, Line 3
The multi-part identifier "users.aspnet_user_id" could not be bound.
View 6 Replies
View Related
Oct 15, 2007
Hello,
I'm having problems with a CLR Trigger trying to get it to work with SQL Server... and i believe it is because permissions... basicly i want to make my trigger get the name of a newly created database and then look for
a table and then see if is empty... then add some rows... thats all...
I have set my databases as Trustworthy and also i have enabled the "clr enabled" parameter...
i mark my project as "Safe" in the Project properties... and it still doesn't work... do i need to
sign my project..? if so.. how?
i'm clueless...
Thank You.!
Code Block
'Table_1' table
- Unable to create table.
A .NET Framework error occurred during execution of user-defined routine or aggregate "Trigger1":
System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host.
The protected resources (only available with full trust) were: All
The demanded resources were: UI
System.Security.HostProtectionException:
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandle rmh, Object assemblyOrString, SecurityAction action, Boolean throwException)
at System.Security.CodeAccessSecurityEngine.CheckSetHelper(CompressedStack cs, PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandle rmh, Assembly asm, SecurityAction action)
at Triggers.Trigger1()
.
The statement has been terminated.
View 3 Replies
View Related
Jan 15, 2007
When the database starts,I want to startup a trigger to do something,how can I do ?
I know there are two kinds of trigger in SQL Server 2005 ,one is DML trigger and the another is DDL trigger
Could you tell me ,Is there a trigger for database level in SQL Server 2005 ?
I know there is this kind of trigger in oracle .
View 3 Replies
View Related
Jan 10, 2008
Hello,I have a form in a web application. When I submit the form it inserts the record into the SQL Server 2005 database. I have an insert trigger. My question is how can i debug the trigger? the trigger then calls a CLR based stored procedure, again how can i debug this CLR stored procedure which gets called by the trigger. Thanks...kindly advice.
View 2 Replies
View Related
Jul 18, 2006
hi
i want to know if row level trigger works with sql 2005.
because in 2000.. only statement level trigger was used.
Thks in advance.
View 3 Replies
View Related
Jul 19, 2006
hi
actually i have a temporay table wich has four columns
say col_1,col_2,col_3,col_4.
so firstly i wud bulk insert from a text file wich mite contain thousands of rows.
then from this temp table col_1 and col_2 shd go to master_a.wich has an identiy column as primary key.
say id,col_1, col_2.
i will have another table detail_b where in there is a foreign key to the table master_a for id.
so it will have f_id, col_3,col_4.
so i am riting a trigger on master_a. so whenver row is inserted in master_a. coresponding id and col 3 col4 shd be inserted into detail_b.
For this in oracle we have row level trigger. where in for each insertion in master a .. correspoding trigger will fire but in sql 2000..
but i wud like to implemtn row level trigger..
can u hlep me out..
View 1 Replies
View Related
Mar 22, 2006
Hello,I am learning SQL Server 2005.I need to create a trigger which increments number of book'spublications:CREATE TRIGGER InsertPublicationON PublicationsAFTER INSERTASBEGINSET NOCOUNT ON;DECLARE @Num smallintSET @Num = SELECT NumPublications FROM Books WHERE ISBN IN(SELECT ISBN FROM inserted);UPDATE BooksSET NumPublications = @Num + 1WHERE ISBN IN(SELECT ISBN FROM inserted);ENDUnfortunately I receive a message:Incorrect syntax near the keyword 'SELECT'.Could you explain me please how to correct the code?I am new to SQL Server.Thank you very much./RAM/
View 2 Replies
View Related
May 31, 2006
Hi,
I simply need a trigger to delete some datasets from a view but have some trouble writing an adequate trigger. Here is my attempt:
Use myDB;
Go
CREATE TRIGGER IO_Trig_Del_myView ON myView
INSTEAD OF Delete
AS
BEGIN
SET NOCOUNT ON
-- Check for dataset, if present delete.
IF (EXISTS (SELECT Z.[myPk]
FROM myTable t, deleted
WHERE t.[myPk] = deleted.[myPk]))
Delete From myTable
Where myTable.[myPk] = deleted.[myPk]...
This causes the following failure:
Msg 4104, Level 16, State 1, Procedure IO_Trig_Del_myView, Line 11
The multi-part identifier "deleted.myPK" could not be bound.
Can somebody explain the reason to me? myPk is part of the View I created. Since I do have three tables in myView so I get that message three times, once per table.
View 5 Replies
View Related
Aug 2, 2006
i have set up
a linked server. i can query the linked server in query analyzer and
also do update/delete. but when i try to run the same query for linked
server through insert trigger, i get following error: [OLE/DB provider returned message. [Microsoft][ODBC Sql Server Driver]Distributed transaction error].btw, i am using Sql server 2000, SP4. main server is windows 2003 server and linked server is windows xp pro.any suggestions will be appreciated.
View 1 Replies
View Related
Jan 18, 2008
Hello,
Does SQL Server 2005 have anything like a "lag" function that, in a sigle query allow you to retrive a previous record? The syntax would be like:
SELECT
transactionid
,transactiondatetime
,amount
,amount + LAG(amount) OVER(ORDER BY transactiondatetime) balance
FROM
bankaccount
Thanks for any advice
View 12 Replies
View Related
Jun 28, 1999
In the SQL 7.0 Documentation is indicated that the UPDATE(<fieldname>), if
used in a isert/update trigger, it return TRUE or FALSE based on presence of <field> in the SET List, if the trigger was fired by an UPDATE operation, or in the list of field to fill, if the trigger was fired by an INSERT operation.
Below there is a piece of code that demostrate the false documentation
assertion in the case of a trigger fired by an INSERT operation, infact even
if i have specified only the FIELD1 in INSERT Statement the trigger Print in the screen that i have touched FIELD2 too.
Now the SP1 don't solve this BUG, even if i had read some month ago (before
that SP1 was out) that in SP1 this will be fixed!
Anyone Can Help me to solve this problem, indicating me where i can post the
problem to sensitize the Microsoft's Service Pack Factory ?
Thank in Advance
PS:Sorry for my Bad English .... correct me please if some part are not
readable!
------[Cut Here]-------------------
CREATE TABLE TEST (FIELD1 INTEGER , FIELD2 INTEGER )
GO
CREATE TRIGGER TriggerIU_Test
ON TEST
FOR INSERT, UPDATE
AS
IF UPDATE(FIELD1) PRINT 'Field 1 Touched'
IF UPDATE(FIELD2) PRINT 'Field 2 Touched'
GO
print 'InsertIng '
INSERT INTO TEST (FIELD1) VALUES (2)
print 'Updating '
UPDATE TEST set FIELD1 = 1
GO
DROP TABLE TEST
------[Cut Here]-------------------
View 2 Replies
View Related
Nov 27, 2007
I have VS 2003 & SQL Server 2005.I have created VB.NET console application which calls various function. Based on data insertion/ updatation in SQL 2005 I need to call function from my VB.NET application. That is from SQL insert/update trigger I need to call function from my console application which is continuouly running.
I need help on how can I capture insert trigger event VS 2003 console application?
View 2 Replies
View Related
Apr 7, 2008
Hey guys,
I have a problem regarding (if it’s the
right way to go about it) triggers in SQL Server 2005 Express. I have already finished
my application but wanted to add this in. My system is a shipping system which
allows users to add data about ships, orders etc. In order for a order to be “put
on� a ship I have created a form which first allows users to select what order
and what ship and then creates a new entry on a table called OrdersonShip. What
I would like my code to do is first check that there is space on the ship (Each
ship has a maxCargo and a currentCargo) and then when the new entry on the
OrdersonShip table is produced I would like the numberofitems field on the
order to be associated with the ship to be added to the currentCargo on the
ship table. How would I go about this?
Many
thanks for any help you can give me.
Peter
View 7 Replies
View Related
Jun 12, 2008
I've this tableCREATE TABLE [dbo].[Attivita]( [IDAttivita] [int] IDENTITY(1,1) NOT NULL, [IDOwner] [int] NULL, [IDAttivitaStato] [varchar](1) COLLATE Latin1_General_CI_AS NULL, [IDAttivitaTipo] [varchar](2) COLLATE Latin1_General_CI_AS NULL, [IDAnagrafica] [int] NULL, [Data] [datetime] NULL CONSTRAINT [DF_Attivita_Data] DEFAULT (getdate()), [Descrizione] [varchar](max) COLLATE Latin1_General_CI_AS NULL, [Privato] [bit] NULL, [LastUpdate] [datetime] NULL CONSTRAINT [DF_Attivita_LastUpdate] DEFAULT (getdate()), CONSTRAINT [PK_Attivita] PRIMARY KEY CLUSTERED ( [IDAttivita] ASC)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]How Can I create a trigger for modify the IDAttività Stato field in specific situaion: if IDAttivitaTipo == OK or == NOIDAttivitaStato must be set to CPlease note that I can write in the IDAttivitaStato field (during my code operation).... but I would like also automatic update if the IDAttivitaTipo is OK or NO Can you help me for create this with a trigger?Thanks
View 2 Replies
View Related
Apr 10, 2008
I need to create either a trigger or stored procedure in SQL server 2005(hopefully someone can tell me).. Here is what I need to happen: I have a table with orders that are generated from a website. After the transaction is completed, I need have the record that was just created also copy to another table. There is a field called flag and the values in this field are either 1 or 2. Imediatly after the transaction occurs, I need the records where flag = 1 to copy to this other table. How would I go about doing this?
View 10 Replies
View Related
May 24, 2008
[SQL Server 2005]
In our system we keep track on all changes that are made by the users.
This means that posts is never deleted, only marked as not "active".
Each table has a SP who takes care of the INSERT/UPDATE.
This SP also calls another SP, which actually does the "inactive" marking of the post.
The question is:
Would it be better (or worse) to have a TRIGGER taking care of this instead?
Occasionally there are data inserted at the "exact" same time (different input sources).
Sometimes there can be a quite heavy workload on the INSERT.
/HÃ¥kan
View 8 Replies
View Related
Jun 10, 2007
I dont have the SQL EXPRESS installed instead I have SQL Standard Edition.
I have two SQL Server instances installed.
1- UserLT (this is sql 2000)2- UserLTSQL2005 (this is SQL 2005 named instance)
But when i try to add a database to my VS website project I get the following error:
Connection to SQL Server files (*.mdf) require SQL server express 2005 to function properly. please verify the installation of the component or download from the URL: go.microsoft.com/fwlink/?linkId=4925
I went in Tools>Opetions>DataBase tools>Data Connection>Sql Server Instance Name (blank for default)
and changed the "SQLEXPRESS" to "USERLTSQL2005".
But I still get the same error message. Any ideas how i can resolve this issue?
View 23 Replies
View Related
Jan 11, 2006
hello,
i've installed SQL server 2005 express and Visual web developper 2005 express.
when i whant to create a database in VWD the following error occures:
connection to SQL Server files (*.mdf) require SQL server express 2005 to function properly. please verify the installation of the component or download from the URL: go.microsoft.com/fwlink/?linkId=49251
i searched the internet but can't find the solution, i already reinstalled my complete workstation but the problem stays.
please help!
View 9 Replies
View Related
Oct 17, 2013
I have a SQL Server database running on a local PC which will eventually be scaled up once everything is working.
The Database takes data from an Access database, then the SQL Server aggregates this data into several other tables.
I have used a trigger to run this in SQL Server, once a table in SQL Server is appended with a specific value.
I have tested the trigger to do a simple task, and this works.
I have tested the aggregation query which create 18 seperate tables as well. It takes around 25 minutes to run. These are huge tables
When I use Access to append the final value to start the SQL Server trigger it freezes and eventually times out. I assume this is because it is running the 25minute trigger, and Access has to wait until this is completed before it can proceed.
I was hoping it would trigger SQL Server to run the trigger, then Access could go off and do something else!
View 10 Replies
View Related
Apr 28, 2006
Hi, all here,
I am just wondering about the Discretization function available on analysis service server (which can not actually discretize data into user-defined expressions) . Isnt it redundant ? I mean since users can discretize their data more meaningfully based on their own expressions in database engine of SQL Server 2005.
Thanks a lot.
View 1 Replies
View Related
May 22, 2008
In my table, column1 having a comma separated values.I want to display in rowwise.
for example:
column1
aa,ss,ff
output should be
aa
ss
ff
Pls. help me..I want to do thr query.
View 22 Replies
View Related
Apr 22, 2008
I have a small problem using the GETDATE() function from a JAVA program using the MS JDBC connector.
When I use the SQL Mangment Studio Express to execute this query:
SELECT GETDATE()
it returns 2008-04-22 16:25:03.690 which is OK !!
I want to get that same value using a Java program so I do that query but when I display it it shows as:
2008-04-22 and there is no time there !
I tried formatting the date to include time but it shows as: 04/22/2008 12:00:00 AM
So maybe the time isn´t there ?
This is the code i am using:
Statement st = con.createStatement();
String sql = "SELECT GETDATE()";
ResultSet result1 = st.executeQuery(sql);
result1.next();
Date today = result1.getDate(1);
Any help would be appreciated.
View 4 Replies
View Related
May 16, 2008
is it possible to do a count on the same column but under different circumstances posting the results in two different result columns?
View 6 Replies
View Related
Mar 6, 2008
Good Evening All,
I've serached this forum and Google'd for a resolution to this issue, to no avail. Here's the scenario:
I'm running VS 2005 on Windows Media Center laptop and need to create ASP.net membership for my web application built using VB. I have SQL Server Developer installed with instance name MSSQLSERVER. Previously, I uninstalled SQL Express and installed Developer edition and can now open and utilize Management Studio.
Now, when I try to create a new SQL Server database in my solution's App_Data directory, I receive the above error. I already changed instance name in VS2005 per Tools-Options-Database Tools-Data Connections to MSSQLSERVER.
Could someone provide me with a list of procedures to ensure proper setup of VS2005 with SQL Server Developer Edition?
Thanks much for your help.
View 5 Replies
View Related
Jul 20, 2005
Is there a way to create a trigger directly on an inline or multi-line tablevalue function?I am trying to create a quick-and-dirty application using an Access DataProject front-end with SQL 2000 SP3 EE.Thanks.
View 2 Replies
View Related
Sep 12, 2007
if service broker is not an option, how can the trigger and sp(s) called by our trigger act asynchronously to the event that fired the trigger in the first place. We are more concerned with the original event being committed than the actions that follow via the trigger.
View 4 Replies
View Related
May 3, 2006
Hi
In SQL Server 2005, does TRIGGER for DML fire per statement or per Record ?
If both, can we define the way it should fires.
thanks / ramanuj
View 11 Replies
View Related