Showing posts with label record. Show all posts
Showing posts with label record. Show all posts

Tuesday, March 27, 2012

Calling Store Procedures

Hi,

I am new to SSIS and just want to know how I can call a store procedure for each record during transformation since my destination table ID is generated by a Store procedure and I must store it also in my integration temp table.

Thanks

Yes, you can call a sproc for each record in the pipeline. Thomas explains how here: http://sqljunkies.com/WebLog/tpagel/archive/2006/01/03/17744.aspx

-Jamie

Thursday, March 22, 2012

Calling External Program from SQL Server 2000

I want to create a file folder on a server when a new record is Inserted
into a SQL Server 2000 table. I was thinking that I would create a simple
windows console application in C# to handle the folder creation. I want to
run that external program from an Insert Trigger on the table. How do I do
that or is there a way to create the folder from within SQL server? Thanks
in advance for any help or guidance given.You could call xp_cmdshell or use SP_OACreate to instantiate a COM object fr
om your trigger. But
don't do that. The insert will be blocked until the trigger has finished, an
d errors will roll back
the insert. I.e., this is a good way to get bad performance. Have the trigge
r insert relevant data
into a table and then let an Agent job run every minute (or so) and read off
of this table and do
whatever needs to be done. If you were on SQL Server 2005, you would use Ser
vice Broker for this,
btw...
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Greg Busby" <gbusby@.med-edge.com> wrote in message news:OWKkkPZWGHA.4972@.TK2MSFTNGP02.phx.
gbl...
>I want to create a file folder on a server when a new record is Inserted in
to a SQL Server 2000
>table. I was thinking that I would create a simple windows console applica
tion in C# to handle the
>folder creation. I want to run that external program from an Insert Trigge
r on the table. How do
>I do that or is there a way to create the folder from within SQL server? T
hanks in advance for any
>help or guidance given.
>

Tuesday, March 20, 2012

Calling another record into this record

This has got to be easier than I am making it out to be. I have a
query that calls on two tables linked by unique ids. I would like to
have the previous outing's # of laps brought into the current outing.
An example of what the view follows
SELECT TOP 100 PERCENT [Main Outing].OutingNumber, [Main
Outing].OutingID, COUNT(dbo.vwLaps.LapTime) AS [# of laps]
FROM dbo.vwOutings [Main Outing] INNER JOIN
dbo.vwLaps ON [Main Outing].OutingID =
dbo.vwLaps.OutingID
GROUP BY [Main Outing].OutingNumber, [Main Outing].OutingID
ORDER BY [Main Outing].OutingNumber DESC

returning
Outing Number Outing ID
# of laps
6{87C29BDC-A2D1-4606-A87B-D456F702BFCE}99
5{203319A9-4B2F-406A-9454-0DD3D5F86211}37
4{B6306DF5-5BF0-4456-8E06-0CD2ED8B1874}54
3{A70643F3-28C2-47CC-B623-4BD6904C2825}95
2{EB409D12-C79C-4D96-BE2A-0BD49C5BE69D}80
1{75D7793D-3239-4544-BACC-84EB564C8638}36
what I woud like is
Outing Number Outing ID
# of laps # of laps previousouting
6{87C29BDC-A2D1-4606-A87B-D456F702BFCE}99 37
5{203319A9-4B2F-406A-9454-0DD3D5F86211}37 54
4{B6306DF5-5BF0-4456-8E06-0CD2ED8B1874}54 95
3{A70643F3-28C2-47CC-B623-4BD6904C2825}95 80
2{EB409D12-C79C-4D96-BE2A-0BD49C5BE69D}80 36
1{75D7793D-3239-4544-BACC-84EB564C8638}36 0
sorry if this is a silly question I'm a little new to this thanks for
any helpOn 15 Jun 2006 05:47:43 -0700, pltaylor3@.gmail.com wrote:

>This has got to be easier than I am making it out to be. I have a
>query that calls on two tables linked by unique ids. I would like to
>have the previous outing's # of laps brought into the current outing.
>An example of what the view follows
>SELECT TOP 100 PERCENT [Main Outing].OutingNumber, [Main
>Outing].OutingID, COUNT(dbo.vwLaps.LapTime) AS [# of laps]
>FROM dbo.vwOutings [Main Outing] INNER JOIN
> dbo.vwLaps ON [Main Outing].OutingID =
>dbo.vwLaps.OutingID
>GROUP BY [Main Outing].OutingNumber, [Main Outing].OutingID
>ORDER BY [Main Outing].OutingNumber DESC
(snip)

Hi pltaylor3,

First, why do you have a "TOP 100 PERCENT" in your query? Since 100
percent equals all rows, you're actually requestin alll rows - which is
the default if you don't specify a TOP clause at all! Get rid of it.

Next, why do you choose aliases that require you to escape the names?
Are you really that fond of typing lots of [ and ] chartacters?

Third, you might also reconsider the "vw" prefixes on your views. In SQL
Server, objects should be named for what they represent, not for how
they happen to be implemented.

Last, here's an answer to your question:

SELECT mo.OutingNumber, mo.OutingID,
COUNT(l.LapTime) AS "# of laps",
(SELECT COUNT(l2.LapTime)
FROM dbo.Outings AS mo2
INNER JOIN dbo.Laps AS l2
ON mo2.OutingID = l2.OutingID
WHERE mo2.OutingNumber = mo.OutingNumber - 1) AS "# of
laps previousouting"
FROM dbo.Outings AS mo -- [Main Outing]
INNER JOIN dbo.Laps AS l
ON mo.OutingID = l.OutingID
GROUP BY mo.OutingNumber, mo.OutingID
ORDER BY mo.OutingNumber DESC

(Untested - see www.aspfaq.com/5006 if you prefer a tested reply)

--
Hugo Kornelis, SQL Server MVP|||(pltaylor3@.gmail.com) writes:
> This has got to be easier than I am making it out to be. I have a
> query that calls on two tables linked by unique ids. I would like to
> have the previous outing's # of laps brought into the current outing.
> An example of what the view follows
> SELECT TOP 100 PERCENT [Main Outing].OutingNumber, [Main
> Outing].OutingID, COUNT(dbo.vwLaps.LapTime) AS [# of laps]
> FROM dbo.vwOutings [Main Outing] INNER JOIN
> dbo.vwLaps ON [Main Outing].OutingID =
> dbo.vwLaps.OutingID
> GROUP BY [Main Outing].OutingNumber, [Main Outing].OutingID
> ORDER BY [Main Outing].OutingNumber DESC

First remove the TOP 100 PERCENT and ORDER BY from the view. They mean
nothing. In SQL 2000 it may seem that a SELECT from the view without
an ORDER BY always return rows according to the ORDER BY in the view,
but that is mere chance. In SQL 2005, this does not happen.

The only way to get sorted output from a query in SQL (no matter the
engine) is to have an ORDER BY clause in the SELECT statment that
outputs the data to the client.

> returning
> Outing Number Outing ID
> # of laps
> 6 {87C29BDC-A2D1-4606-A87B-D456F702BFCE} 99
> 5 {203319A9-4B2F-406A-9454-0DD3D5F86211} 37
> 4 {B6306DF5-5BF0-4456-8E06-0CD2ED8B1874} 54
> 3 {A70643F3-28C2-47CC-B623-4BD6904C2825} 95
> 2 {EB409D12-C79C-4D96-BE2A-0BD49C5BE69D} 80
> 1 {75D7793D-3239-4544-BACC-84EB564C8638} 36
> what I woud like is
> Outing Number Outing ID
> # of laps # of laps previousouting
> 6 {87C29BDC-A2D1-4606-A87B-D456F702BFCE} 99 37
> 5 {203319A9-4B2F-406A-9454-0DD3D5F86211} 37 54
> 4 {B6306DF5-5BF0-4456-8E06-0CD2ED8B1874} 54 95
> 3 {A70643F3-28C2-47CC-B623-4BD6904C2825} 95 80
> 2 {EB409D12-C79C-4D96-BE2A-0BD49C5BE69D} 80 36
> 1 {75D7793D-3239-4544-BACC-84EB564C8638} 36 0
> sorry if this is a silly question I'm a little new to this thanks for
> any help

SELECT MO.OutingNumber, MO.OutingID,
COUNT(L.LapTime) AS [# of laps],
COUNT(L2.LapTime) AS [# of prev laps],
FROM dbo.vwOutings MO
JOIN dbo.vwLaps L ON MO.OutingID = dbo.vwLaps.OutingID
LEFT JOIN (dbo.vwOutings MO2
JOIN dbo.vwLaps L2 ON MO2.OutingID = L2.OutingID)
ON MO.OutingNumber = MO2.OutingNumber + 1
GROUP BY MO.OutingNumber, MO.OutingID

Bur this is a complete guess about what your tables and data are like. If
it does not work out, please post:

o CREATE TABLE statements for your tables.
o INSERT statements with the sample data.

Some narrative how the tables are organised would help too.

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

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Monday, March 19, 2012

Calling a Stored Procedure on Multiple Records

I have a stored procedure on an SQL Server database which displays statistical data for a single record. The example below selects a user ID as a parameter and displays the user's name and the total amount of transactions he has made:
CREATE PROCEDURE dbo.GetUserStats @.UserID BIGINT AS
DECLARE @.TempTable TABLE
(
UserID BIGINT,
UserName VARCHAR(60),
TotalAmt FLOAT
)

INSERT INTO @.TempTable (UserID, UserName, TotalAmt)
SELECT u.RecID, u.LastName + ', ' + u.FirstName,
(SELECT SUM(t.Amount) FROM Transactions t WHERE t.UserID = @.UserID)
FROM Users u
WHERE u.RecID = @.UserID

SELECT * FROM @.TempTable
GO

So if I execute this amount entering a single ID, it returns a single row for that user:

UserID UserName TotalAmt
--------
1 Doe, John 100.00

What I would like to do is create another stored procedure which calls this one for every user returned in a query, thus returning the same data for several users:

UserID UserName TotalAmt
--------
1 Doe, John 100.00
2 Smith, Bob 123.45
3 Blow, Joe 150.55

Is there a way to re-use a stored procedure within another, based on the results of a query?Some thoughts:

1. This sounds more like a function than a stored procedure. Would make the execution concept much easier (ie, SELECT dbo.MyFunction(MyUserID) FROM MyTable).

2. You could wrap this with another stored procedure; you could pass in the user list as a parameter (there was an excellent article recently over at SQLServerCentral.com about using an xml string as a parameter).

But I really think that what you want is a function.

Regards,

hmscott|||Thanks for your feedback.

I'm not familiar with functions. Would I want to convert GetUserStats to a function?|||may, maybe not. you do know you can do that whole thing without the temp table.

BTW, bigint for userid? do you know there are not that many people in the world?|||I'm not familiar with functions. Would I want to convert GetUserStats to a function?

I wouldn't "convert" per se; at least not the way that you have written it.
Try this:

Open Query Analyzer
Click on File | New
Double click on Create Function
Double click on Create Scalar Function

Read in SQL BOL about Scalar functions.

I think you will get an idea of what a function is and how to go about writing your own. From there I think you will find it easier to understand how to proceed.

Regards,

hmscott|||may, maybe not. you do know you can do that whole thing without the temp table.

BTW, bigint for userid? do you know there are not that many people in the world?
The example I posted is very simplified. The actual query I'm trying to pull off is pretty complicated and pulls data from several tables, that's why I included the temp table. Can I use a temp table in a function?

Yeah, I guess a BIGINT is more than I need for a user ID. I had the misconception of thinking INTs only go to 32,000 when I set up this database (as they do in many programming languages).|||I have tried building a few functions. I can get them to run using a direct statemtent such as:

SELECT * FROM MyFunction(1)

But If I try to use the line above in a stored procedure or another function, I get an error:

Invalid object name 'MyFunction'.|||They're fiesty. You need the user name as a prefix, as in:SELECT *
FROM dbo.MyFunction(1)-PatP

Sunday, March 11, 2012

calling a procedure from another procedure

Maybe this isn't possible, but I'm trying to figure out how to call a procedure in a select statement where I can pass a new id each record found. Here is the procedure code that returns the desired results for any given ID:

CREATE PROCEDURE proc_amEnrollmentTrackingDetailGet_cst
@.syStudentID INTEGER
AS

DECLARE
@.SATACT DATETIME,
@.HSTranscript DATETIME,
@.AcceptLetter DATETIME,
@.FAFSA DATETIME,
@.FinAidApp DATETIME

--Get the last DateDue for each document type

SELECT
@.SATACT = CASE WHEN cmDocTypeID IN (81,110) THEN DateDue END,
@.HSTranscript = CASE WHEN cmDocTypeID IN (83) THEN DateDue END,
@.AcceptLetter = CASE WHEN cmDocTypeID IN (126) THEN DateDue END,
@.FAFSA = CASE WHEN cmDocTypeID IN (150) THEN DateDue END,
@.FinAidApp = CASE WHEN cmDocTypeID IN (155) THEN DateDue END
FROM
cmDocument (NOLOCK)
WHERE
syStudentID = @.syStudentID
ORDER BY
cmDocTypeID, DateDue

-- Return the results

SELECT
S.syStudentID,
S.StuNum,
@.SATACT AS SATACT,
@.HSTranscript AS HSTranscript,
@.AcceptLetter AS AcceptLetter,
@.FAFSA AS FAFSA,
@.FinAidApp AS FinAidApp,
S.FirstName,
S.LastName
FROM
syStudent S (NOLOCK)

WHERE S.syStudentID = @.syStudentID
GO

Now maybe there is a better way to do this, but what I want to do is to call the above procedure and have it return a row for every ID in the following code:

SELECT DISTINCT
S.syStudentID
FROM
syStudent S (NOLOCK)
JOIN cmActivity_vw A (NOLOCK)
ON A.syStudentID = S.syStudentID
AND A.cmTemplateID IN (16,195,283,290,291) --Application received
WHERE
S.StartDate BETWEEN '5/1/07' AND '9/1/07' -- Expected Start Date
AND S.amPrevEducID = 1 --High School Grad
AND S.syCampusID = 5 --Main Campus

Create a table valued function instead of a procedure.

See SQL Server 2005 Books Online topics:
CREATE FUNCTION (Transact-SQL)
http://msdn2.microsoft.com/en-us/library/ms186755.aspx

Using APPLY
http://msdn2.microsoft.com/en-us/library/ms175156.aspx

|||

Why do you even need a stored procedure? Why not merely use a larger query, e.g.,
SELECT
S.syStudentID,
S.StuNum,
CASE WHEN cmDocTypeID IN (81,110) THEN DateDue END as SATACT,
CASE WHEN cmDocTypeID IN (83) THEN DateDue END as HSTranscript,
CASE WHEN cmDocTypeID IN (126) THEN DateDue END as AcceptLetter,
CASE WHEN cmDocTypeID IN (150) THEN DateDue END as FAFSA,
CASE WHEN cmDocTypeID IN (155) THEN DateDue END as Fin AidApp,
S.FirstName,
S.LastName
FROM syStudent S (NOLOCK)
INNER JOIN
(SELECT DISTINCT
S.syStudentID
FROM syStudent S (NOLOCK)
JOIN cmActivity_vw A (NOLOCK)
ON A.syStudentID = S.syStudentID
AND A.cmTemplateID IN (16,195,283,290,291) --Application received
WHERE S.StartDate BETWEEN '5/1/07' AND '9/1/07' -- Expected Start Date
AND S.amPrevEducID = 1 --High School Grad
AND S.syCampusID = 5 --Main Campus
) TMP
on S.syStudentID = TMP.syStudentID
INNER JOIN cmDocument D (NOLOCK)
ON
D.syStudentID = S.syStudentID

Dan

|||

Dan:

One reason to use a stored procedure instead of a function is to encapsulate security -- specifically to dis-allow ad hoc ability to table yet still provide needed functionality. We have a number of clients that have in their standards that (1) rank-and-file users must not have any access to table components of databases and (2) all database data access be given by another means -- such as stored procedures or functions. There are also other reasons.

|||

Waldrop,

I certainly agree that if the user cannot use a Query that includes a sub-Query, because it violates some security regulation, then the solution I proposed is unsatisfactory.

I could not tell from the preceding posts that such security issues were involved, so I suggested what seems to me to be the simplest solution to obtain the desired dataset.

Dan

|||

Ok, I have created the following function:

CREATE FUNCTION dbo.fn_amEnrollmentTrackingDetailGet_cst (@.syStudentID INTEGER)
RETURNS @.amTrackingDetail TABLE (
syStudentID INTEGER,
SATACT DATETIME,
HSTranscript DATETIME,
AcceptLetter DATETIME,
FAFSA DATETIME,
FinAidApp DATETIME)
AS

BEGIN
DECLARE
@.SATACT DATETIME,
@.HSTranscript DATETIME,
@.AcceptLetter DATETIME,
@.FAFSA DATETIME,
@.FinAidApp DATETIME

SELECT
@.SATACT = CASE WHEN cmDocTypeID IN (81,110) THEN DateDue END,
@.HSTranscript = CASE WHEN cmDocTypeID IN (83) THEN DateDue END,
@.AcceptLetter = CASE WHEN cmDocTypeID IN (126) THEN DateDue END,
@.FAFSA = CASE WHEN cmDocTypeID IN (150) THEN DateDue END,
@.FinAidApp = CASE WHEN cmDocTypeID IN (155) THEN DateDue END
FROM
cmDocument (NOLOCK)
WHERE
syStudentID = @.syStudentID
ORDER BY
cmDocTypeID, DateDue

INSERT INTO @.amTrackingDetail
SELECT
S.syStudentID,
@.SATACT AS SATACT,
@.HSTranscript AS HSTranscript,
@.AcceptLetter AS AcceptLetter,
@.FAFSA AS FAFSA,
@.FinAidApp AS FinAidApp
FROM
syStudent S (NOLOCK)

WHERE S.syStudentID = @.syStudentID
RETURN
END

But when I try to reference that function in a SELECT statement like:

SELECT
dbo.fn_amEnrollmentTrackingDetailGet_cst(SyStudentID)
FROM
syStudent

I get: Invalid object name 'dbo.fn_amEnrollmentTrackingDetailGet_cst'.

|||

Charles:

You have defined a "Table valued function" and in your select statement you are referencing it like a "scalar function." Look at the CREATE FUNCTION article in books online to see the difference.

|||

This is an example using a table function from the 2005 AdventrueWorks database.

SELECT C.*

FROM HumanResources.Employee AS E

CROSS APPLY dbo.ufnGetContactInformation(EmployeeID)AS C

|||

Dan,

Thank you very much for your post. It was very helpful, especially here at the beginning of this project when we are verifying the dataset for accuracy. However, another reason that I am attracted to the function paradigm is that it seems that it would allow me to easily reference that function in other solutions.

|||

Charles:

Try altering your function call to something like:

select tf.syStudentID,
tf.SATACT,
tf.HSTranscript,
tf.AcceptLetter,
tf.FAFSA,
tf.FinAidApp
from syStudent a
cross apply fn_amEnrollmentTrackingDetailGet_cst(SyStudentID) tf

|||

I also saw another example of this at http://msdn2.microsoft.com/en-us/library/ms186755.aspx, but when I try the following code with a declared table, I get 'Line 22: Incorrect syntax near 'APPLY'.

DECLARE @.TableApplied TABLE (
syStudentID INTEGER)

INSERT @.TableApplied
SELECT DISTINCT
S.syStudentID
FROM
syStudent S (NOLOCK)
JOIN cmActivity_vw A (NOLOCK)
ON A.syStudentID = S.syStudentID
AND A.cmTemplateID IN (16,195,283,290,291) --Application received
-- and A.eventstatus = 'Closed'
WHERE
S.StartDate BETWEEN '8/1/07' AND '9/1/07' -- Expected Start Date
AND S.amPrevEducID = 1 --High School Grad
AND S.syCampusID = 5 --Main Campus

SELECT
C.*
FROM
@.TableApplied AS A
CROSS APPLY dbo.fn_amEnrollmentTrackingDetailGet_cst(A.SyStudentID) AS C

|||I noticed that the database compatibility level has to be 90 in order for CROSS APPLY to work. Ours is set to 80 and 90 is not an option in the drop down. :(|||If you are in 80 compatibility and cannot use CROSS APPLY, consider something like modifying your function to accept a NULL studentID as an argument; when a null student id is sent to the UDF return all of the rows from the table instead of rows for the specific student. Then you can INNER JOIN this to your syStudent table based on StudentID?

Sunday, February 19, 2012

Calculation including previous record value

Hi,
How can I do calculation on the SQL Server that would include previous
record.
e.g.
a,b field in the table
if a is first record, then a= b
else
a = a(previous record value)+ b
Thank you for help
Schapopa
*** Sent via Developersdex http://www.examnotes.net ***Hi
CREATE TABLE #Test (col1 INT NOT NULL PRIMARY KEY, col2 INT NOT NULL)
INSERT INTO #Test VALUES (1,100)
INSERT INTO #Test VALUES (2,500)
INSERT INTO #Test VALUES (3,800)
INSERT INTO #Test VALUES (4,900)
SELECT *,(SELECT SUM(col2) FROM #Test as q
WHERE m.col1 >= q.col1 )AS total
FROM #Test AS m
<schapopa> wrote in message news:u7kCv1lRGHA.336@.TK2MSFTNGP12.phx.gbl...
> Hi,
> How can I do calculation on the SQL Server that would include previous
> record.
> e.g.
> a,b field in the table
> if a is first record, then a= b
> else
> a = a(previous record value)+ b
> Thank you for help
> Schapopa
>
>
> *** Sent via Developersdex http://www.examnotes.net ***