Showing posts with label output. Show all posts
Showing posts with label output. Show all posts

Thursday, March 22, 2012

Can TSQL query create new output column ?

How can i write a query to split a database column and shows 2 new columns. In my database column

I have 2 mixing items and need to split out to 2 columns. Normally I have to write a query and change parameter

and run another query.

For example a database column with average number and range number.

Thanks

Daniel

Can you post some DDL, sample data and expected results?

AMB

|||

Hai,

Can you try the below query, and let me know that, it relates to your requirement or not:

DECLARE @.Columns varchar(1000)

SET @.Columns = ''

-- Create a temporary table.

CREATE TABLE #TempTable(Items varchar(50))

INSERT INTO #TempTable(Items) VALUES('A')

INSERT INTO #TempTable(Items) VALUES('A')

INSERT INTO #TempTable(Items) VALUES('A')

INSERT INTO #TempTable(Items) VALUES('B')

INSERT INTO #TempTable(Items) VALUES('B')

INSERT INTO #TempTable(Items) VALUES('B')

INSERT INTO #TempTable(Items) VALUES('C')

INSERT INTO #TempTable(Items) VALUES('C')

INSERT INTO #TempTable(Items) VALUES('D')

INSERT INTO #TempTable(Items) VALUES('D')

-- Before

SELECT * FROM #TempTable

-- Make a column list

SELECT

@.Columns = @.Columns + '[' + Items + '], '

FROM #TempTable

GROUP BY Items

-- Check the column values exits or not.

IF ( @.Columns IS NOT NULL ) AND ( @.Columns <> '' )

BEGIN

DECLARE @.Query nvarchar(1000)

SELECT @.Columns = SUBSTRING(@.Columns,1, LEN(@.Columns)-1)

SELECT @.Query = '

SELECT

*

FROM

(

SELECT

Items

FROM #TempTable

) AS Dummy

PIVOT

(

MAX(Items)

FOR Items IN (' + @.Columns + ')

)AS PvtTable'

EXEC(@.Query)

END

-- Drop the temporary table.

DROP TABLE #TempTable

Please clarify If I did any wrong.

Regards,

Kiran.Y

|||

Perhaps something like:

SET NOCOUNT ON

DECLARE @.MyTable table
( RowID int IDENTITY,
MyGroup int,
MyValue decimal(10,2)
)

INSERT INTO @.MyTable VALUES ( 1, 25 )
INSERT INTO @.MyTable VALUES ( 2, 5 )
INSERT INTO @.MyTable VALUES ( 1, 10 )
INSERT INTO @.MyTable VALUES ( 1, 15 )
INSERT INTO @.MyTable VALUES ( 1, 4 )
INSERT INTO @.MyTable VALUES ( 2, 6 )
INSERT INTO @.MyTable VALUES ( 2, 11 )
INSERT INTO @.MyTable VALUES ( 2, 0 )
INSERT INTO @.MyTable VALUES ( 1, 12 )

SELECT
Average = cast( avg( MyValue ) AS decimal(10,2)),
Range = ( cast( min( MyValue ) AS varchar(10)) + '-' +
cast( max( MyValue ) AS varchar(10)))
FROM @.MyTable
GROUP BY MyGroup

Average Range
13.20 4.00-25.00
5.50 0.00-11.00

|||

Hi Kiran

Thanks for answering my email. To clarify this below are my tables and columns and my query

Table: Item Stat_label Stat_value

column: Pack ID Stat_label_ID Stat_value_ID

Pack_Num Label ( has 2 rows Value

Ave and Range)

My query to list Pack_Num, Ave and it's value

SELECT Item.Pack_Num, Stat_label.Label, Stat_value.Value

FROM Item, Stat_label, Stat_value

WHERE Item.packID=Stat_label.Stat_label_ID AND

Stat_label.Stat_lavel_ID=Stat_value.Stat_value_ID

AND Stat_label.Label= Ave

My question: I want a query to list Pack_Num, Ave, Range and value

How can I do it?

That's mean this query need to split the Stat_label and list another

column name"Range".

Thanks
Daniel

|||

If you are using SQL 2005, look into the PIVOT function.

If you are using SQL 2000, explore using CASE.

Maybe these articles will help:

Pivot Tables -A simple way to perform crosstab operations
http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1131829,00.html

Pivot Tables - How to rotate a table in SQL Server
http://support.microsoft.com/default.aspx?scid=kb;en-us;175574

Pivot Tables -Dynamic Cross-Tabs
http://www.sqlteam.com/item.asp?ItemID=2955

Pivot Tables - Crosstab Pivot-table Workbench
http://www.simple-talk.com/sql/t-sql-programming/crosstab-pivot-table-workbench/

|||

Thanks all

I can not use "insert" because my account for this is read only and I avoid to list everything in a column and and use Excel pivot to summary.

Daniel

|||

Daniel,

If you would carefully examine the code provided, you will see that the INSERT statements are only building a sample table so that we could demonstrate a query suggestion.

You didn't bother to provide the table DDL, or sample data, so we have to waste our time creating sample data for you. and apparently, you can't read and understand example code.

|||

This may be closer to what you are hoping to find:

SELECT

i.Pack_Num,

sl.Stat_Label,
Average = cast( avg( sv.Stat_Value ) AS decimal(10,2)),
Range = ( cast( min( sv.Stat_Value ) AS varchar(10)) + '-' +
cast( max( sv.Stat_Value ) AS varchar(10)))
FROM Item i

JOIN Stat_Label sl

ON i.Pack_ID = sl.Stat_Label_ID

JOIN Stat_Value sv

ON sl.Stat_Label_ID = sv.Stat_Value_ID

WHERE sl.Label = 'Ave'
GROUP BY

i.Pack_Num,

sl.Stat_Label

|||

Thanks Anrnie but It is not working

Error at Average= cast......

Error at Range= (cast......

My Average and Range are decimal, no need cast

Do I have to declare a temp table?

Daniel

|||

Actually, it appears that the Stat_Value is most most likely a varchar().

Before we can help you any further, please post the table DDL and some sample data in the form of INSERT statements. Please refer to this link for help in preparing your material.

|||

Can SQL query create a new column or not?. DO NOT want to make a temp table.

Thanks

Daniel

|||

Can TSQL create a new column at the output?

If not I need 2 select statement but how to joint them? Can not use EXCEPT in TSQL? Tried to use UNION but

the results in one column.

It's complicated with creating a temp table since I do not know how to insert to temp table from database.

Thanks


Daniel

|||Please supply the requested information. (See my previous post.)

Tuesday, March 20, 2012

Can this be done with an output parameter?

Hi I want to make a Function in my User class that adds new members into the db. What I want to do is add the users details in using a stored procedure and input parameters and then return a parameter indicating their userid value and set it to a variable.

My userid column in the my db is auto incrementing with a seed of 1 and a step value of 1.

How could I create an output parameter that would return their new user id and then how would i set it to an integer variable.

Thanks::How could I create an output parameter that would return their new user id and then how
::would i set it to an integer variable

do you mean from the front end or inside the stored proc ?

if you mean the stored proc:


create procedure <name> ( @.param1 nvarchar(25),@.param2 int, @.userid int OUTPUT)
as

insert into ( ....) values (...) select @.userid=@.@.IDENTITY
..


HTH|||Use the OUTPUT Parameter of the Stored Procedure. Refer to SQL Server BOL for further assitance ...|||Hi yeah I mean by using the output param in the sp.

How does the @.@.Idendity work then?

How would i set this to a varialble in my front end. Would I use

Dim UserID as Integer

Dim objParam as New SqlParameter("@.@.Idendity", SqlDbType.Int)
objParam.Direction = ParameterDirection.Output
objParam.Value = UserID
objComm.Parameters.Add(objParam)

Thanks|||First, you should use SCOPE_IDENTITY(), not @.@.IDENTITY.

Next, use a SP like this:


create procedure <name> ( @.param1 nvarchar(25),@.param2 int, @.userid int OUTPUT)
as

insert into ( ....) values (...)

select @.userid=SCOPE_IDENTITY()

then


Dim objParam as New SqlParameter("@.UserID", SqlDbType.Int)
objParam.Direction = ParameterDirection.Output
objComm.Parameters.Add(objParam)

Then after the command is run, check objComm.Parameters("@.UserID") for the UserID|||Many thanks Douglas. We may have to start calling you superman on here lol as you come to everyones rescue.|||Thanks. I do have the glasses, though no cape, and no one wants to se me in tights<g>.

Monday, March 19, 2012

Can the Output parameter length be more than 8000 characters?

Hi!
I am running one SP - which needs to return strings, seperated by
delimitter. I am using output parameter of type Varchar (8000). I learned
that this is maximum length allowed.
Now what problem I am facing is, for a particular field, the delimitted text
is getting higher than 8000 characters and that is why the rest of the value
is getting truncated.
Can you guys let me know any better way of achieving this?
I will be extremely thankful to you.
Regards,
SachinYou'll have to select the data instead of using an output param... Or
upgrade to SQL Server 2005 and use VARCHAR(MAX) instead :)
Adam Machanic
Pro SQL Server 2005, available now
http://www.apress.com/book/bookDisplay.html?bID=457
--
"Sachin Vaishnav" <SachinVaishnav@.discussions.microsoft.com> wrote in
message news:880D2034-115A-4E86-9D38-97BD909BF564@.microsoft.com...
> Hi!
> I am running one SP - which needs to return strings, seperated by
> delimitter. I am using output parameter of type Varchar (8000). I learned
> that this is maximum length allowed.
> Now what problem I am facing is, for a particular field, the delimitted
> text
> is getting higher than 8000 characters and that is why the rest of the
> value
> is getting truncated.
> Can you guys let me know any better way of achieving this?
> I will be extremely thankful to you.
> Regards,
> Sachin|||Instead of Varchar(8000) ... how about using TEXT or NText as your datatype?
Best Regards
Vadivel
http://vadivel.blogspot.com
http://thinkingms.com/vadivel
"Sachin Vaishnav" wrote:

> Hi!
> I am running one SP - which needs to return strings, seperated by
> delimitter. I am using output parameter of type Varchar (8000). I learned
> that this is maximum length allowed.
> Now what problem I am facing is, for a particular field, the delimitted te
xt
> is getting higher than 8000 characters and that is why the rest of the val
ue
> is getting truncated.
> Can you guys let me know any better way of achieving this?
> I will be extremely thankful to you.
> Regards,
> Sachin|||Thanks. Using 2005 is not possible for me now. I will have to manage fromw
what I have already :)
Anyways, as per your other suggestion, the problem in that is, I am already
having one select returned out of the SP. So, there is no point in that also
.
Can some cursor type of output or XML type of output is useful to me?
I need to send it back to the API and the API is used by UI.
Help me,
Sachin
"Adam Machanic" wrote:

> You'll have to select the data instead of using an output param... Or
> upgrade to SQL Server 2005 and use VARCHAR(MAX) instead :)
>
> --
> Adam Machanic
> Pro SQL Server 2005, available now
> http://www.apress.com/book/bookDisplay.html?bID=457
> --
>
> "Sachin Vaishnav" <SachinVaishnav@.discussions.microsoft.com> wrote in
> message news:880D2034-115A-4E86-9D38-97BD909BF564@.microsoft.com...
>
>|||Stored procedures can return multiple rowsets... Why not use two?
Adam Machanic
Pro SQL Server 2005, available now
http://www.apress.com/book/bookDisplay.html?bID=457
--
"Sachin Vaishnav" <SachinVaishnav@.discussions.microsoft.com> wrote in
message news:DB3F424E-01C2-49DB-B7B7-99D22F91CD24@.microsoft.com...
> Thanks. Using 2005 is not possible for me now. I will have to manage fromw
> what I have already :)
> Anyways, as per your other suggestion, the problem in that is, I am
> already
> having one select returned out of the SP. So, there is no point in that
> also.
> Can some cursor type of output or XML type of output is useful to me?
> I need to send it back to the API and the API is used by UI.
> Help me,
> Sachin
> "Adam Machanic" wrote:
>|||"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:Ogxg9Nr7FHA.1416@.TK2MSFTNGP09.phx.gbl...
> Stored procedures can return multiple rowsets... Why not use two?
...or use multiple Output parameters.
When one reaches the 8000 character limit, insert the rest in the 2nd.
But I'd prefer Adam's solution, 2 recordsets.|||Hi!
Thanks a lot. Is it possible to have 2 RS from SP? Well, I was unable to get
once. Can I have some example of the same?
Thanks
Sachin
"Adam Machanic" wrote:

> Stored procedures can return multiple rowsets... Why not use two?
>
> --
> Adam Machanic
> Pro SQL Server 2005, available now
> http://www.apress.com/book/bookDisplay.html?bID=457
> --
>
> "Sachin Vaishnav" <SachinVaishnav@.discussions.microsoft.com> wrote in
> message news:DB3F424E-01C2-49DB-B7B7-99D22F91CD24@.microsoft.com...
>
>|||Sure...
CREATE PROCEDURE TWO_RESULT_SETS
AS
BEGIN
SELECT 1
SELECT 2
END
GO
EXEC TWO_RESULT_SETS
GO
DROP PROCEDURE TWO_RESULT_SETS
GO
--
Adam Machanic
Pro SQL Server 2005, available now
http://www.apress.com/book/bookDisplay.html?bID=457
--
"Sachin Vaishnav" <SachinVaishnav@.discussions.microsoft.com> wrote in
message news:FD089362-31C1-49B2-83B0-88ED1F9FD5FC@.microsoft.com...
> Hi!
> Thanks a lot. Is it possible to have 2 RS from SP? Well, I was unable to
> get
> once. Can I have some example of the same?
> Thanks
> Sachin
> "Adam Machanic" wrote:
>|||Thanks a lotl!
However, I know this. But i guess, the problem is perhaps, when I write 2
selects in the SP, if I am using ADODB.Recordset to retrieve the data, I
won't get the result of both the record set. Right?
So, can you suggest me how do I tackle that one? :)
Thanks again!
Regards,
Sachin
"Adam Machanic" wrote:

> Sure...
> --
> CREATE PROCEDURE TWO_RESULT_SETS
> AS
> BEGIN
> SELECT 1
> SELECT 2
> END
> GO
> EXEC TWO_RESULT_SETS
> GO
> DROP PROCEDURE TWO_RESULT_SETS
> GO
> --
> --
> Adam Machanic
> Pro SQL Server 2005, available now
> http://www.apress.com/book/bookDisplay.html?bID=457
> --
>
> "Sachin Vaishnav" <SachinVaishnav@.discussions.microsoft.com> wrote in
> message news:FD089362-31C1-49B2-83B0-88ED1F9FD5FC@.microsoft.com...
>
>|||Set rsSecond = rsFirst.NextRecordset()
cheers,
</wqw>

Sunday, March 11, 2012

Can SSIS parse this text report without a lot of programming?

I've got some machines that output text files after each shot of parts. I'd like to take the data in those files and parse it and insert it into a SQL Server database for future massaging. The text files look like the example I've posted below. Can SSIS parse out the set points and actual values even though the file isn't CSV or tab delimited and the data is kind of 'strewn' all over the report? Each report does have the exact same format so the report format doesn't change from report to report, just the data. Thanks in advance.

Ernie

WP4.57 C Y C L E P R O T O C O L

Order data 18.05.06 11:27:57

Order number : 2006 Recipe no. : 15761

Machine number : 7 Recipe name : Stabilizer Bar Innsulator

Machine Operator: 1257 Art.descrip.: Stabilizer Bar Grommet

Shot Volume : 285.8

Part quantity : 100096 Type of mat.: M370-34

Shot quantity : 782 Batch number: 20124-125

-

Temperatures in ?C

Set Act Set Act

Fixed heat.platen right 182 182 Tempering screw 83 83

middle 180 180 Tempering inject.cylinder 85 85

left 182 182 Tempering circuit 3 90 91

Tempering circuit 4 0 39

Movab.heat.platen right 182 182 Tempering circuit 5 0 39

middle 180 180

left 182 182 Mould temperature 1 0 39

Mould temperature 2 0 39

Third heat.platen right 0 39 Mould temperature 3 0 39

middle 0 39 Mould temperature 4 0 39

left 0 39 Mould temperature 5 0 39

Mould heating circuit 6 0 39 Compound temp.after screw 104 104

Mould heating circuit 7 0 39 Compound temp.after nozzle 0 39

Mould heating circuit 8 0 39

Mould heating circuit 9 0 39

Mould heating circuit 10 0 39

Times in sec

Injection time 51.20 Transfer time 1 2.00

Internal mould press.time 0.00 Transfer time 2 2.00

Dwell pressure time 7.00 Transfer time 3 2.00

Controlled cure time 180.00 Transfer time 4 2.00

Calculated cure time 0.00 Transfer time 5 2.00

last cycle time 276

last opening time 25

Measure when injecting Measure at injection end

max. injection speed mm/s 11.9 Injection length mm 2.0

Injection energy kNm 247.2 Injection time sec 51.20

max. int.mould pres. bar 2 Hydraulic pressure bar 190

max. dwell pressure bar 192 Internal mould pressure bar 0

Pad mm 0.4

Stock Temperatures and Pressures During Metering

Stock Temperatures(C) Set Actual Metering Pressures(bar) Set Actual

Temperature 1st Step 105 106 Pressure 1st Step 135 131

Temperature 2nd Step 105 106 Pressure 2nd Step 135 129

Temperature 3rd Step 105 105 Pressure 3rd Step 135 122

Temperature 4th Step 105 106 Pressure 4th Step 135 135

Temperature 5th Step 105 109 Pressure 5th Step 135 137

Protocol Complete

Yes absolutely, SSIS can do this. Import it as a single, very wide, column and parse out the various sections in the pipeline. Given the complexity you're probably going to have to do this in an aysnchronous script component.

-Jamie

Can SQLServer produce Excel Spreadsheet output ?

Deaa group,

I am using SQLServer 2000 in an XP Sp2. I would like to do the
following:

I have a program running on a database server that generates some data
which are loaded to the database. This program is used in a web
application, invoked by some java program and JSP scripts. (I am
frontend illiterated.)

The question is, is it possible to write a stored procedure to generate
output in excel spreadsheet? So that user could call this procedure
and get spreadsheet output on the client side.

Any pointer to a solution would be immensely apprecaited.

thanks,
charia<cpeters5@.gmail.com> wrote in message
news:1120580708.814110.191080@.z14g2000cwz.googlegr oups.com...
> Deaa group,
> I am using SQLServer 2000 in an XP Sp2. I would like to do the
> following:
> I have a program running on a database server that generates some data
> which are loaded to the database. This program is used in a web
> application, invoked by some java program and JSP scripts. (I am
> frontend illiterated.)
> The question is, is it possible to write a stored procedure to generate
> output in excel spreadsheet? So that user could call this procedure
> and get spreadsheet output on the client side.
> Any pointer to a solution would be immensely apprecaited.
> thanks,
> charia

As far as I know, there's no direct way to export to an .xls from a stored
proc. DTS can export data to Excel, and you can execute a package from a
stored proc in various ways:

http://www.sqldts.com/default.aspx?210

By using ActiveX steps in a DTS package, you could control all the details
of the .xls file name, structure, column headers etc. via the Excel COM
interface, but you would need to actually install Excel on the server in
order to do that, which may not be possible (or desirable).

Another option would be calling bcp.exe via xp_cmdshell to create a CSV or
tab-delimited file. In the end, the easiest solution might be to find a Java
or JSP module of some sort which can export to Excel - then you just return
the result set to the client or middle tier as usual, and let it create the
file, which is probably a cleaner solution than dealing with presentation in
the database itself.

Simon|||i know ASP can generate an xls from data selected by a SP. i bet there
is some way JSP can do it as well, i'm just not a web developer =P

Friday, February 24, 2012

Can someone help me in understanding the output of this TSQL script

declare @.startdate datetime

declare @.enddate datetime

declare @.testvalue datetime

set @.startdate = '2005-12-31'

set @.enddate = '2006-12-29'

set @.testvalue ='2006-05-17'

if convert(varchar(20), @.testvalue, 102) between convert(varchar(20), @.startdate, 102) and convert(varchar(20), @.enddate, 102)

print 'yes'

else

print 'no'

-

The above script print yes with format specifier as 102 where as it prints no with format specifier as 102. Why/how does the format specifier affect the output?

I agree that there are better was of achieving what is done in the above script. But I am curious to know the why sql server behaves this way in the above query.

Thanks

Take a look at the output of the following SQL:

declare @.startdate datetime
declare @.enddate datetime
declare @.testvalue datetime
set @.startdate = '2005-12-31'
set @.enddate = '2006-12-29'
set @.testvalue ='2006-05-17'

SELECT Mode = 'No Format', TestVal = convert(varchar(20), @.testvalue),
StartVal = convert(varchar(20), @.startdate),
EndVal = convert(varchar(20), @.enddate)
UNION ALL
SELECT 'Format 102', convert(varchar(20), @.testvalue, 102),
convert(varchar(20), @.startdate, 102),
convert(varchar(20), @.enddate, 102)

This gives the following results:


No Format | May 17 2006 12:00AM | Dec 31 2005 12:00AM |Dec 29 2006 12:00AM
Format 102 | 2006.05.17 | 2005.12.31 | 2006.12.29

As you can see the no format provides date text strings which do not sort alphabetically in date order at all. Format 102 produces a text string which does sort in date order when sorted alphabetically so can be used in the comparison. Of course the simple way to do it is to perform the comparison directly on the date data.

|||

I agree with your explanation for format specifier 102. However, This means that my script in the first thread should work with the format specifier as 101. But it doesnt. Can you explain this behaviour please?

|||

If you are comparing date values, you 'should NOT' be converting to varchar!

It is wasted effort and slows your process down.

|||

That's the reason i mentioned in my first post that we can do this in a better way. I am of the opinion that we have to use datetime instead of varchar(20).

But what i want to know is why does the change in format specifier (in my query) change the output value.

With 101 format specifier the expression evaluates to false where as with 102 it evaluates to true. Need to know/understand this behaviour of SQL server wrt the format specifier change.

|||

For exactly the same reason - again this is a text-based comparison.

Here are the strings you are comparing, ordered alphanumerically ascending:

--102
2005.12.31 - @.startdate
2006.05.17 - @.testvalue
2006.12.29 - @.enddate

--101
05/17/2006 - @.testvalue
12/29/2006 - @.enddate
12/31/2005 - @.startdate

It's clear to see that in the second example, @.testvalue < @.enddate. In fact using format 101 makes your BETWEEN condition impossible to meet.

Chris

|||Thanks Chris!

can somebody please help me with my query?

Hi I'm creating a macro to show how many times a user has logged into our database within a month. The output should look like this :

Name

Kit
Peter
Jeny
Katie
Patricia

Last Login date
Dec 28 2004 07:12AM
Dec 28 2004 09:30AM
Dec 27 2004 10:23AM
Dec 28 2004 10:38AM
Dec 27 2004 10:30AM

Login count
12/26/04
0
0
1
0
0

Login count
12/27/04
1
0
1
1
1

Login count
12/28/04
1
1
0
1
0

Right now my query reflects Name, last login date and the current day login count:

Select a.username, a.login_dt, CASE WHEN
a.isactive = 1 and a.login_dt = current_date() THEN 1
ELSE 0
END
from cms.dbo.usagelog a, cms.dbo.sys_user c
where a.userid = c.user_id and c.group2 IN ('DIS', 'MD', 'PC', 'SYS')
ORDER BY c.group2, a.login_dt, a.username

and this is the OUTPUT:
Name

Kit
Peter
Jeny
Katie
Patricia

Last LOGIN Date
Dec 28 2004 07:12AM
Dec 28 2004 09:30AM
Dec 27 2004 10:23AM
Dec 28 2004 10:38AM
Dec 27 2004 10:30AM

Login COUNT 12/28/04 (CURRENT DAY)
1
1
0
1
0

Can somebody please show me how i can do a loop or an iteration inside my query and get it to show the current day's data and all the data from the previous days (ex. 12/23, 12/24, 12/25, 12/26, 12/27) .You could try using 'GROUP BY':
Select A.Username, A.Login_Dt, Count(*) As Login_Times
From Cms.Dbo.Usagelog A, Cms.Dbo.Sys_User C
Where A.Userid = C.User_Id And C.Group2 In ('Dis', 'Md', 'Pc', 'Sys')
Group By A.Username, A.Login_Dt
Order By C.Group2, A.Username, A.Login_Dt :D|||LKBrwn_DBA, i don't think you can ORDER BY a column in a GROUP BY query if that column isn't in the SELECT list|||LKBrwn_DBA, i don't think you can ORDER BY a column in a GROUP BY query if that column isn't in the SELECT list
True, I kind'a just copied over the ORDER BY ... should have looked more closely.
:o