Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Wednesday, March 28, 2012

How to create Parameter Field with embedded SQL

I want to create an expression field on my report that performs an sql statement that I specify to bring back a total instead of using the built-n functions for SSRS, how can I do this? Basically just like in Crystal where you can create a formula field that runs a sql statement then brings back a value from your sql statement. This value is not related to the other data in the report...so yes in theory you may be thinking subreport...is tha the only way? or can I create some sort of textbox that shows the total I want below?

DECLARE @.TotalDaysInMonth int,

@.today datetime,

@.TotalWeekendDays int,

@.TotalHolidaysThisMonth int,

@.TotalPostingDays int

SET @.today = GETDATE()

-- TOTAL DAYS THIS MONTH

SET @.TotalDaysInMonth = CASE WHEN DatePart(mm,GetDate()) IN (1,3,5,7,8,10,12) THEN

31

ELSE

DateDiff(day,GetDate(),DateAdd(mm, 1, GetDate()))

END

SELECT @.TotalDaysInMonth

-- TOTAL HOLIDAYS THIS MONTH

SELECT @.TotalHolidaysThisMonth = (SELECT COUNT(*) FROM Apex_ReportingServer.dbo.Holidays

WHERE HolidayDate BETWEEN (DATEADD(DAY, -DATEPART(DAY, @.today) + 1, @.today))

AND (DATEADD(DAY, -DATEPART(DAY, @.today), DATEADD(MONTH, 1, @.today))))

SELECT @.TotalHolidaysThisMonth

-- TOTAL # WEEKEND DAYS THIS MONTH

DECLARE @.date DATETIME

SET @.date = '20060101'

SELECT @.TotalWeekendDays = 8 +

CASE WHEN ISDATE(CONVERT(CHAR(6), @.date, 112) + '29') = 1 THEN

CASE WHEN DATENAME(WEEKDAY, CONVERT(CHAR(6), @.date, 112) + '01') IN ('Saturday', 'Sunday')

THEN 1 ELSE 0 END ELSE 0 END +

CASE WHEN ISDATE(CONVERT(CHAR(6), @.date, 112) + '30') = 1 THEN

CASE WHEN DATENAME(WEEKDAY, CONVERT(CHAR(6), @.date, 112) + '02') IN ('Saturday', 'Sunday')

THEN 1 ELSE 0 END ELSE 0 END +

CASE WHEN ISDATE(CONVERT(CHAR(6), @.date, 112) + '31') = 1 THEN

CASE WHEN DATENAME(WEEKDAY, CONVERT(CHAR(6), @.date, 112) + '03') IN ('Saturday', 'Sunday')

THEN 1 ELSE 0 END ELSE 0 END

SELECT @.TotalWeekendDays

SELECT @.TotalPostingDays = @.TotalDaysInMonth - (@.TotalHolidaysThisMonth + @.TotalWeekendDays)

SELECT @.TotalPostingDays

You could simply add the SQL Statement above to a new/different Dataset and reference that Dataset in the given field on your report...does that make sense, or am I missing something?

|||exactly thanks! I actually tried that and it worked before you posted...thanks you were right on.

How to create Parameter Field with embedded SQL

I want to create an expression field on my report that performs an sql statement that I specify to bring back a total instead of using the built-n functions for SSRS, how can I do this? Basically just like in Crystal where you can create a formula field that runs a sql statement then brings back a value from your sql statement. This value is not related to the other data in the report...so yes in theory you may be thinking subreport...is tha the only way? or can I create some sort of textbox that shows the total I want below?

DECLARE @.TotalDaysInMonth int,

@.today datetime,

@.TotalWeekendDays int,

@.TotalHolidaysThisMonth int,

@.TotalPostingDays int

SET @.today = GETDATE()

-- TOTAL DAYS THIS MONTH

SET @.TotalDaysInMonth = CASE WHEN DatePart(mm,GetDate()) IN (1,3,5,7,8,10,12) THEN

31

ELSE

DateDiff(day,GetDate(),DateAdd(mm, 1, GetDate()))

END

SELECT @.TotalDaysInMonth

-- TOTAL HOLIDAYS THIS MONTH

SELECT @.TotalHolidaysThisMonth = (SELECT COUNT(*) FROM Apex_ReportingServer.dbo.Holidays

WHERE HolidayDate BETWEEN (DATEADD(DAY, -DATEPART(DAY, @.today) + 1, @.today))

AND (DATEADD(DAY, -DATEPART(DAY, @.today), DATEADD(MONTH, 1, @.today))))

SELECT @.TotalHolidaysThisMonth

-- TOTAL # WEEKEND DAYS THIS MONTH

DECLARE @.date DATETIME

SET @.date = '20060101'

SELECT @.TotalWeekendDays = 8 +

CASE WHEN ISDATE(CONVERT(CHAR(6), @.date, 112) + '29') = 1 THEN

CASE WHEN DATENAME(WEEKDAY, CONVERT(CHAR(6), @.date, 112) + '01') IN ('Saturday', 'Sunday')

THEN 1 ELSE 0 END ELSE 0 END +

CASE WHEN ISDATE(CONVERT(CHAR(6), @.date, 112) + '30') = 1 THEN

CASE WHEN DATENAME(WEEKDAY, CONVERT(CHAR(6), @.date, 112) + '02') IN ('Saturday', 'Sunday')

THEN 1 ELSE 0 END ELSE 0 END +

CASE WHEN ISDATE(CONVERT(CHAR(6), @.date, 112) + '31') = 1 THEN

CASE WHEN DATENAME(WEEKDAY, CONVERT(CHAR(6), @.date, 112) + '03') IN ('Saturday', 'Sunday')

THEN 1 ELSE 0 END ELSE 0 END

SELECT @.TotalWeekendDays

SELECT @.TotalPostingDays = @.TotalDaysInMonth - (@.TotalHolidaysThisMonth + @.TotalWeekendDays)

SELECT @.TotalPostingDays

You could simply add the SQL Statement above to a new/different Dataset and reference that Dataset in the given field on your report...does that make sense, or am I missing something?

|||exactly thanks! I actually tried that and it worked before you posted...thanks you were right on.sql

Monday, March 26, 2012

How to create INSERT query for contents of table

Using Sql Server 2005 Express and Management Studio I need to createa SQL insert statement for the contents of a table (FullDocuments) sothat I can run the query on another server with that same table schema(FullDocuments) and the contents will automatically be inserted intothe new instance of the FullDocuments table.

In Management StudioI have used "Script Table as" for the create table query. Thesecond instance of FullDocuments has been created on the remoteserver. Now how do I generate an insert query for the contents ofFullDocuments so that the contents can be moved/inserted to the newinstance of the table?

Thanks for any help provided.

Why not just do something like :

insert into fulldocuments2

select * from server1.fulldocuments1

|||

Hi Partha. Thanks for the suggestion.

The problem is that the fulldocuments2 is on a web server whilefulldocuments1 is on my local machine which does not allow me to uploada table or db directly. I need to transfer the data by SQL querybut don't how to generate a sql insert statement that contains all thedata from fulldocuments1 without manually typing it. For smalldata inserts I can do that. But this time it involves thousandsof lines of text, so I am hoping for a simple automated way to createthe sql insert statement to move the data.

|||

Just export the data in fulldocuments1 to a flat file and import into fulldocuments2 using Export Import wizard

|||

I can't find the Export Import Wizard. I am using the Express version of SQL Server 2005 and Management Studio.

|||

use bcp to copy out the data and copy it back in the web server

http://msdn2.microsoft.com/en-us/library/ms162802.aspx

|||

The web server admin to which i need to import data only allows dataimport via Query Analyzer (hence sql insert statement) or via CSVfile. Since I am having no luck generating a sql insert statementthat contains the data, it looks like I need to focus on how to createa CSV file with the data content. I have been studying the BCPdocumentation from your link, but don't see any means for generating aCSV file using BCP.

What are my options for creating a CSV file containing the data from the source table?

|||

See this link for an example of bcp to create csv file

http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/

|||

Consider writing a very short app (20 lines or so) using SqlBulkCopy. It's incredibly easy and incredibly fast.

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx

http://davidhayden.com/blog/dave/archive/2006/01/13/2692.aspx

|||

Hi Buddha. Thanks for the links. The first one uses VB so I have tried that for my app. I like theconcept of uploading directly to the web server db but am getting thiserror message when I click the button to upload the data:

An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Iam a novice at this and realize I am bumping up against a securityissue, but don't know how to solve it. Any help would beappreciated. Here is the VB code for my app:

Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page

Dim connectionString1 As String = "Data Source=_x_connection string to local db_x_"
Dim connectionString2 As String = "Data Source=_x_connection string to web server db_x_"

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

' Open a connection to the source database.
Using sourceConnection As SqlConnection = _
New SqlConnection(connectionString1)
sourceConnection.Open()

' Perform an initial count on the destination table.
Dim commandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.Category;", _
sourceConnection)
Dim countStart As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)

' Get data from the source table as a SqlDataReader.
Dim commandSourceData As SqlCommand = New SqlCommand( _
"SELECT * " & _
"FROM Category;", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader

' Open the destination connection.
Using destinationConnection As SqlConnection = _
New SqlConnection(connectionString2)
destinationConnection.Open()

' Set up the bulk copy object.
' The column positions in the source data reader
' match the column positions in the destination table,
' so there is no need to map columns.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(destinationConnection)
bulkCopy.DestinationTableName = _
"Category"

Try
' Write from the source to the destination.
bulkCopy.WriteToServer(reader)

Catch ex As Exception
Console.WriteLine(ex.Message)

Finally
' Close the SqlDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
reader.Close()
End Try
End Using

' Perform a final count on the destination table
' to see how many rows were added.
Dim countEnd As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Ending row count = {0}", countEnd)
Console.WriteLine("{0} rows were added.", countEnd - countStart)

Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Using
End Using
End Sub
End Class

|||

Although I would have liked to have gotten the app approach to work so that I could learn more, the practical solution to my problem is the free Database Publishing Wizard provided by Microsoft. Amongst the various options it provides is one that creates a sql file with complete insert query for all the data in the db, etc. Thanks for the input which has gotten me thinking about new possibilities for future projects.

how to create index (Case when)

How to create index when there is a SQL statement like
Select count(1) as [Total],
sum(Case when Field1 < Field2 then 1 else 0 End) as [Selected]
from Table1
Thx in Adv
XLDBUse one index on each column ( field 1 field 2 ) ...use nonclustered for each

however, if table is small ( say less than 1000 row s ) SQL probably wont use indexes..it will scan whole table.|||the table has 2 million records|||actually, there are 2 similar tables that i use the query on...

the table with 2 million records is taking 57 seconds
the table with 40,000 records is taking 1 second

there is only 1 index on "Field1" in "Case When" statement

Wednesday, March 21, 2012

How to create a table (structure) based on a result of a stored procedure

following statement will not work ..SELECT * INTO #xxx FROM (EXECUTE
sp_storedprocedure)
instead of select you can use INSERT INTO will work
eg:
create table #t(i int)
insert into #t exec myproc
create proc myproc
as
select 1
vinu
"Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
news:ueWGWKyAHHA.1012@.TK2MSFTNGP04.phx.gbl...
> Dear all,
> There is a stored procedure that returns a result set consisting of some
> 30
> columns of different types.
> How can I automatically (i.e. not by means of CREATE TABLE statement)
> create
> a table with a structure that correspons to the returned result set?
> I mean something like:
> SELECT * INTO #xxx FROM (EXECUTE sp_storedprocedure)
> (The above unfortunately doesn't work).
> To be specific: the stored procedure in question is:
> sp_MSenum_replication_agents @.type = 4, @.exclude_anonymous = 1
> Any help would be greatly appreciated!
> Thank you in advance.
> Best regards,
> Andrew
>
Well .. it is not possible to use select into...exec
vt
"Andrew Drake" <andrewdrake@.hotmail.com> wrote in message
news:OXdJJayAHHA.4328@.TK2MSFTNGP03.phx.gbl...
> As I wrote, the idea is to create the table automatically, i.e. NOT to use
> the CREATE TABLE statement.
> Best regards,
> Andrew
>
> "vt" <vinu.t.1976@.gmail.com> wrote in message
> news:%23GSuhRyAHHA.4672@.TK2MSFTNGP02.phx.gbl...
>
sql

How to create a select statement with an increasement variable?

Example:

Select icount + 1 as icount from table

or

Select counter() as icount from table

The above is wrong ...just a sample to show what I am trying to accomplish.

Is there a function in SQL statement? Thanks.No, this unfortunately is not possible.

The solution I've seen to this is to create either a #Temp table (or better, a table variable) with an Identity column and the other columns you need, and then INSERT your resultset into it. This will give you the incrementing column you are looking for.

Alternately, add this counter in the front end (on your ASP.NET page).

Terri|||The reason I can't add the counter in the front end because I am doing paging.

Thanks for your help. I think I will create #temp table to solve my problem.sql

Monday, March 19, 2012

How to create a select statement with an increasement variable?

Example:

Select icount + 1 as icount from table

or

Select counter() as icount from table

The above is wrong ...just a sample to show what I am trying to accomplish.

Is there a function in SQL statement? Thanks.No, this unfortunately is not possible.

The solution I've seen to this is to create either a #Temp table (or better, a table variable) with an Identity column and the other columns you need, and then INSERT your resultset into it. This will give you the incrementing column you are looking for.

Alternately, add this counter in the front end (on your ASP.NET page).

Terri|||The reason I can't add the counter in the front end because I am doing paging.

Thanks for your help. I think I will create #temp table to solve my problem.