Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Need To Union And Group Split Databases


We had a divestiture within our company. Now what used to be contained in one database in now split into two databases. One showing all history and one being all current data as of 6/1/2008. Is there an easy way to Union or Join these? Right now I'm currently doing a simple UNION ALL, but can't group the two select statements:

SELECT
Year,Location,QtySold
FROM
historydb

UNION ALL

SELECT
Year,Location,QtySold
FROM
currentdb

Can't do a subset and group both of these selects. How would some of you pro's do this? Right now I can put this in a simple view and then create a SP off of this view that would do this grouping, but it seems like I should be able to do it all in one query. Thanks.




View Complete Forum Thread with Replies

Related Forum Messages:
UNION With A Max On Split Date/Time Fields
I have 2 tables, each with one ID field, a separate
Date and Time fields and a number of other fields.
The tables contain duplicates on the ID field.
I want to do a UNION keeping only the record with the latest
Date and Time.

This would work:
SELECT MyTab.myKeyField, Max(MyTab.myDate) AS myDate
FROM (SELECT myKeyField, myDate
from Table1
union
SELECT myKeyField, myDate
from Table2) AS MyTab
GROUP BY MyTab.myKeyField

But is only taking care of Date, not Time (some records have
the same date but different times)
The other problem is, when I add more fields, I have to
include them in the GROUP BY clause, and this way I end up
with duplicates (because some other fields have different
values)

Is there a way to do this?

View Replies !
Split A Specific Group
 

Hi everyone, I'm working with SSRS 2000 and I have my report grouped by  =Fields!ID.Value , but each ID has just the ID#, or an A or OT at the end. EX. ID# 12345, is divided and shows me like if there are 3 different Employees: 12345, 12345-A, and 12345-OT.   I want 12345 and 12345-A, to be grouped in one, and 12345-OT, be displayed seperately. Is this possible? Do I have to write a special command??? all help is useful so please help.
 
Thanks,
 
Abner

View Replies !
When To Split Up Databases?
I'm converting our companies binary file data to SQL Server data.  I'm a developer, not a dba, and can't seem to get my company to hire a dba, so I need some advice from the community. I have an application running right now, it looks like it will take a week to run.  Here's my estimates of the database size once it 's finished being loaded:
Database Size: 20 Gig
Largest Table (# of rows): 15 million rows
Number of Tables: 37
Other Details: I'm going to use Web Merge Replication to replicate filtered data to 500 customers.

QUESTION:
At what point do I need to consider splitting the database up onto multiple servers?

Or, is it better to split up the database into multiple databases on one server?

Someone suggested to me to split up each customers data into a separate database on the server (i.e. ~500 databases).  Is this an accepted practice?

View Replies !
GROUP BY And UNION Problem
I have a table named "task" with columns [task_name], [task_body], [task_from], [task_to].

And I have multiple records like below
task_name1,task_body1, task_from1, to_name1
task_name1,task_body1, task_from1, to_name2
task_name1,task_body1, task_from1, to_name3
task_name1,task_body1, task_from1, to_name4

and so on...

I want to group these tasks as below

task_name1,task_body1, task_from1, (to_name1,to_name2,to_name3,to_name4)

Please help me the query. I have tried using GROUP BY and UNION, but it doesn't help

Thanks all!

View Replies !
Another 'keep Together' Problem/group Split Across Page Break
How can I stop a group from being split across 2 pages?


1 table group
1 detail group consisting of 2 rows, can be N number of these per table group

e.g.
TG1
DG1row1
DG1row2
DG2row1
DG2row2
...
DGnrow1
DGnrow2

TG2
DG1row1
DG1row2
DG2row1
DG2row2
...
DGnrow1
DGnrow2
<--page break should occur here-->

TG3
DG1row1
DG1row2
DG2row1<--but it is actually appearing somewhere like this-->
DG2row2
...
DGnrow1
DGnrow2

If TG can fit on one page, then it should do so

I can't put a page break after a group, as it may only be 4 rows, this would be too wasteful

View Replies !
How To Group/list Top 3 Of Each Category W/o Using Union?
Hello,So my table contains say 100,000 records, and I need to group thecategories in fld1 by the highest count of subcategories. Say fld1contains categories A, B, C, D, E.All of these categories contain subcategories AA, AB, AC, AD,...AJ, BA,BB...BJ, CA, CB, CC...CJ, etc in fld2.I am counting how many subcategories are listed for each category. LikeA may contain 5 of AA, 7 of AB, 3 of AC, 11 of AD...1 for the rest and20 of AJ. B may contain 2 of BA, 11 of BB, 7 of BC, and 1 for the rest.I want to pick up the top 3 subcategory counts for each category. Wouldlook like this:Cat SubCat CountA AJ 20A AD 11A AB 7B BB 11B BC 7B BA 2So event though each category contains 10 subcategories, I only want tolist the top 3 categories with the highest counts as above. If I justdo a group by and sort I can get this:Cat SubCat CountA ... ...AAAAAA...B ... ...BBBBB...But I just want the top 3 of each category. The only way I can think ofto do this is to query each category individually and Select Top 3, andthen Union these guys into one query. The problem is that I have tohardcode each category in the Union query. There may be new categoristhat I miss. Is there a way to achieve what I want without using Union?Thanks,Rich*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View Replies !
UNION With GROUP BY 'Invalid Column Name'
 
I have a query similar to the following, but it gives the following error:
'Invalid column name 'GroupName'.'
 

SELECT 'Primary' as GroupName, City

FROM PrimaryTable

UNION ALL

SELECT SpecialGroupName AS GroupName, City

FROM Table2

GROUP BY GroupName, City

 
GroupName is varchar(30)
 
Any ideas why this would fail.  Thanks in advance.
 
Terry
 
 
 

View Replies !
Using Group By Clause In Union Query
Hi all,

I have two table having datas like

Table1
--------------------------------------------------------------------
A            C1            C2            C3             C4
--------------------------------------------------------------------
x             0              0              3                2    
x             0              1              0                2    
x             0              0              2                1    
y             1              5              2                0


Table2
--------------------------------------------------------------------
A            C1            C2            C3             C4
--------------------------------------------------------------------
x             0              0              1                4    
y             1              0              3                1
y             1              2              0                0
y             0              0              5                1

select * from(
select A,C1,C2,C3,C4 from Table1 group by A
union
select A,C1,C2,C3,C4 from Table2 group by A
)as t

Result:
--------------------------------------------------------------------
A            C1            C2            C3             C4
--------------------------------------------------------------------
x             0              1              5                5    
y             1              5              2                0    
x             0              0              1                4    
y             2              2              8                2    

But i need the result like i.e grouped by column 'A'
--------------------------------------------------------------------
A            C1            C2            C3             C4
--------------------------------------------------------------------
x             0              1              6                9    
y             3              7             10               2    

select * from(
select A,C1,C2,C3,C4 from Table1 group by A
union
select A,C1,C2,C3,C4 from Table2 group by A
)as t group by A

The above query gives the following error
 [Error Code: 8120, SQL State: S1000]  Column 't.C1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Please help me out.

-Anand

View Replies !
Standard Way To Union Tables In Different Databases?
What is the standard way to union tables with exactly the same schema that are in different databases?

For example:





Code Block

USE db1 SELECT * FROM table1
UNION
USE db2 SELECT * FROM table2

this will return the following error:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'use'.

View Replies !
Alternative To Creating View With Union In Two Databases?
I attempted to create a view in SQL Server 2000 that Unions twoqueries. The first part of the query gets data from the local server,the second part gets info from a linked server. (The query works finein Query Analyzer.)I received this error when I tried to save the query:ODBC error: [Microsoft][ODBC SQL Server Driver] The operation couldnot be performed because the OLE DB provider 'SQLOLEDB' was unable tobegin a distributed transaction.[Microsft][ODBC SQL Server Driver][SQL Server][OLE/DB providerreturned message: New transaction cannot enlist in the specifiedtransaction coordinator.]After a little reading I discovered the "Database limitation":"A view can be created on a table only in the database the viewcreator is accessing".That's my problem... is there a simple solution or alternative tocreating a view?Thanks,Matt

View Replies !
Split The Existing MDF File Into Mutliple Files As A File Group?
I have a huge MDF File - 120 GB File (Had setup as 1 MDF initially) -- Did not anticipate that the DB would grow to that size!!

Anyways.. I heard that the general performance woul grow if i had them as "File Groups"..

Is there anyway - to split the existing MDF file into Mutliple files as a File Group?

Where should i start? Can someone please direct me..

View Replies !
How Does &&"union/union All&&" Work Inside SQL Server?
 

Why the sequence different?
 
 

select * from (

select id=3,[name]='Z'

union all select 1,'G'

union all select 2,'R'

union all select 4,'Z'

) as t

order by [name]

--result:

---------

--1 G

--2 R

--4 Z

--3 Z

select * from (

select id=3,[name]='Z'

union select 1,'G'

union all select 2,'R'

union all select 4,'Z'

) as t

order by [name]

--result:

----------

--1 G

--2 R

--3 Z--changed

--4 Z

View Replies !
Union All Does Not Union All Rows
Hi all,

I have a Union All transformation with 4 inputs and one output when I debug the package the sum of the different inputs rows does not match the row count in output.

I don't understand, I've used the Union All transform many times and I've never seen this.

Any idea why this could happen ?  

View Replies !
Inner Group Header Repeats After Page Break Caused By Outer Group
 

Hi,
 
I have a simple report containing a table with a grouping. The group has a header row. I had a requirement to display a fixed no of rows in a page. In order to acomplish that I created an outer group with expression as "Fix((RowNumber("tblReportBody")-1)/10)". The approach is fine and I am able to successfully insert page break after the required no of rows.
 
The issue I am facing is after the page break the group headers of inner group is getting displayed which I do not want. I want to display group header only if the group changes.
 
 
--------------------------------------------------------------------------------------------------
Without outer group (used for page break)
--------------------------------------------------------------------------------------------------
Page: 1
 Inner Group header1 (visible)
  Details...
<normal page break>
 
Page: 2
   Details...

 
 Inner Group header2 (visible)
  Details...
 
--------------------------------------------------------------------------------------------------
Without outer group (used for page break)
--------------------------------------------------------------------------------------------------
Page: 1
Outer Group header (Hidden)
 Inner Group header1 (visible)
  Details...
<force break by outer group>
 
Page: 2
 Inner Group header1 (visible)
  Details...

 
 Inner Group header2 (visible)
  Details...

--------------------------------------------------------------------------------------------------
 
I would appreciate if you can suggest a way in which I can achive conditional page break without repeating inner group headers on next page.
 
Thank you
Sabyasachi Bose

View Replies !
What's Microsoft Doing About Providing Page Numbering Per Group And Total Pages Per Group?
Hi!
 
    I've posted a feedback with Microsoft to see if we can get them to fix the issue described below, but so far no one from Microsoft has commented to let us know what they're doing about this problem!   I'm posting this here to see if maybe we can get more people to rate this feedback or chime in on what a pain it is!  Please feel free to add your own comments or how you had to work around this issue and whether or not you think this is something Microsoft should be addressing NOW.
 

https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=311679
 
Provide Individual Page Numbering per Group and Total Pages per Group
 
Currently in a Reporting Services report, you can't readily reset the page number for each group in a table, nor can you display the total number of pages per group. For example, if I'm printing invoices and each invoice is a separate group, I'd like to be able to print "Page 1 of 5" , "Page 2 of 5" etc. for the first invoice, then "Page 1 of 3" when the next invoice begins, and so on. This was easy in Crystal Reports. I realize that Crystal Reports has a two-pass process that enables that kind of pagination. However, this is REALLY important functionality that's just missing from Reporting Services and I'm hoping you'll provide it REALLY SOON! Yeah, I know there are work-arounds if you can know exactly how many rows of information there are on each page. But gosh! That's not practical, especially if you have second level groups inside the main group or text blocks in rows that can 'grow' to more than one line. I've read a couple of work-arounds, but none of them works correctly and consistently when more than one user is running the same report or when you print the report while you're looking at it on the screen. I still may need access to the overall report page number and the overall total number of pages, so don't get rid of that. It's just that if you're doing this already for the entire report, I don't see why you can't do it per group! Lots of people have been asking for this for years, and I don't understand why it hasn't been implemented.
 
 
I've read a few articles on this topic, but no one has come up with a decent work around.  My theory is that Microsoft should be addressing this immediately.  This is major functionality that's just plain missing from SSRS and should have been there from the start.  If anyone from Microsoft can let us know what's going on with this issue or if anyone would like for me to clarify this further, feel free to let me know.

 
Thanks!
Karen

View Replies !
Group Beneath Recursive Group Problem. Is This A Bug Or Am I Missing Something In Regards To Scope?
I have an RDL with two groups.  The first group is a recursive group for divisions and offices.  The second group is on employees.  I want a hierachical report showing total hours for division, office and employee.  The recusrive groups works fine and gives me the correct total for division and office.  The second groups gives me the correct employees but they each have the total of the office they are within.  Example data set is
 
Loc              Emp         Hrs        Date           ParentLoc
 
Div
DivA-NY        John         5           1/1/2008    Div
DivA-NY        John         3           1/2/2008    Div
DivA-NY        Mary         6           1/1/2008   Div
DivA-LA        Mike         2           1/1/2008    Div
DivA-LA        Mike         1           1/2/2008    Div
DivA-LA        Tom          4           1/1/2008    Div

 
The result rendered is;
 
DIV       21
   DIV-NY  14
      John      14
           1/1/2008   5
            1/2/2008  3
      Mary      14
           1/1/2008   6
   DIV-LA    7
      Mike       7
          1/1/2008    2
          1/2/2008    1
      Tom       7
          1/1/2008     4
 
The first group is grouped on Loc with a parent of ParentLoc.  The summation of hours is sum(fields!hrs,"table1_Group1",recursive)
 
The second group is grouped on employee.  The summation of hours is sum(fields!hrs).  I have also tried addeing scopes of both group 1 and 2 but that has no effect.
 

View Replies !
Error 15401: Windows NT Group Or Group Not Found
I have a user in SQL Server with a NT login of Mike
I changed his NT account to Mikel in User Manager

Now when I try to add Mikel, Im getting error 15401.

Do I need to delete NT login in SQL Server 'Mike' account first ?..before adding 'Mikel' ?

Can I go into the Master database and just change Mike login to Mikel ?

Thank you

View Replies !
Login For Domain Local Group And Global Group
I have one domoain in the forest.  The domain level is set to Windows 2000 native mode and forest level is set to mixed mode.  My SQL server 2005 server joined to this domain.   I added a brand new domain local group and add a normal user account to this domain local group.  I login to the SQL server 2005 server and make a query "SELECT * FROM sys.login_token".  I cannot see my domain local group in sys.login_token.  However, if I add my account to a global group, I can see it there.

Then, I setup another forest.  This time, I have domain level set to Windows 2003 mode and forest level is set to Windows 2003 native mode.  I do the same testing.  This time, I can see my domain local group in sys.login_token.

Why does SQL server 2005 has this limitation?  Is it a bug?

View Replies !
Hiding Column Group Based On Row Group In Matrix...
I have a matrix that has a row group with page break after each and a column group.  I want to show only certain columns when row group is equal to (something).  Is this possible?

 

View Replies !
Any Way To Show A Group Detail Header Row Once For Each Group In A Table?
I have a need to show a row inside a table group to simulate a header row for the data rows inside the group.  The table will not have a real header or footer.  Thanks for the help.

View Replies !
Adding A Group By Clause And Getting A Count Of A Group
HiI am new to SQL and am having a problem. I need to fix my query to do the following...2) get a total of the number of rows returned.
DECLARE @StartDate varchar(12)DECLARE @EndDate   varchar(12)DECLARE @Region    varchar(20)
SET @StartDate = '01/01/2002'SET @EndDate   = '12/31/2008'SET @Region    = 'Central'
SELECTA.createdon,A.casetypecodename,A.subjectidname,A.title,A.accountid,A.customerid,A.customeridname,B.new_Region,B.new_RegionName
FROM  dbo.FilteredIncident AINNER JOIN dbo.FilteredAccount B ON A.customerid = B.accountid
WHERE (A.createdon >=@StartDate  AND A.createdon <= @EndDate)AND   (B.new_RegionName = @Region)AND   (A.casetypecode = 2) 
 

View Replies !
How?: Group By Date And Count Rows In Group
I'm new to MSSQL 2005 and want to get a summary of a log table. I want to count all the rows for each date based on a DATETIME field called 'post_date' that holds the date and time of each record's creation.

this is the best I can come up with:

Code:


SELECT
DISTINCT(LEFT(post_date,11)) AS post_date, COUNT(DISTINCT(LEFT(post_date,11))) AS total_posts
FROM log_directory_contacts
GROUP BY post_date



The results show each date but the count column ('total_posts') returns '1' for every row even when I know their are more than 1 record on that date.

What am I doing wrong? Thanks!

View Replies !
Repeat First Row Group Header For Second Row Group Items
I have a matrix with two row groups and one column group with about 6 items in it.  I have about 2100 rows at the lowewst row group level.  This report was built solely for excel export.  The first row group has about 20 items and controls the visibility of the other group.  When I toggle the visibility of the second row group, how can I make the the header of the first row group copy down for each row of the other row group? The first row group is the Section and the second is Mnemonic.

 

Example:

 Now:




Code Snippet
                               Column    Column
Section1 -

                  Mnemonic

                  Mnemonic

                  Mnemonic

                  Mnemonic

Section2 -

                  Mnemonic

                  Mnemonic

                  Mnemonic

                  Mnemonic

 

 

Should be:


Code Snippet

                                 Column    Column

Section1 -

Section1     Mnemonic

Section1     Mnemonic

Section1     Mnemonic

Section2 -

Section2     Mnemonic

Section2     Mnemonic

Section2     Mnemonic

 

View Replies !
How Can I Show A Row Inside A Table Group Just Once After The Group Row?
I have a need to show a row inside a table group to simulate a header row for the data rows inside the group.  The table will not have a real header or footer.  Thanks for the help.

View Replies !
How To Use Group By (group Tasks Based On Projects)
Hi folks,

               I have a Projects , each project have many tasks now i want to display tasks replated to each project:

for example:

            

 

 

    Project1-------------------->task1

                                              task2

                                               task3

                                              task4

 

Project2----------------------->task4

                                              task5

                                              task6

 

 

.............................................projectN.....................

 

 

how to write query for this

 

i have 2 tables:

Project .......>columns are projectid

Task------------->columns are projectid, taskid

|


 

View Replies !
Linking Tables From Different Databases Or Querying From Multiple Databases
Dear Readers,Is it possible, like in Access, to link to tables in other SQL databases that are on the same server? I have a query that I originally had in Access that queered from multiply databases. It did this by having those other tables in the other databases linked to the database that had the query. 
 

View Replies !
T-SQL Problem...selecting TOP 1 Of Each GROUP In GROUP BY?
Hi,I was hoping someone may be able to help me with a tricky T-SQLproblem.I need to come up with a SELECT statement that does basically thefollowing:Select RCRD_REFNO, MAX(MODIF_DTTM) as MODIF_DTTM from[StageDb].[dbo].tblPersonInfo group by RCRD_REFNOHowever, I need to select ONLY the TOP 1 of each group (i.e. only 1record for each unique RCRD_REFNO). The problem is of course that if Iadd 'top 1' after select, it only brings back 1 record full stop,rather than 1 for each group!Now, I have previously come up with a similar query that DOES do thissuccessfully, but it relies on a criteria (such as a unique identifier)-unfortunately, the nature of the table I'm using for this currentjob means that it actually doesn't have a primary key, as it'ssimply a staging area for raw data, and can even have completelyidentical records in it. I think the only way I'm going to be able todo it is to literally use the 'TOP' command somehow, but am notsure how to adapt the above to implement it...I'd be very gratefulfor any advice.Many thanks

View Replies !
Adding SubTotol Of A Group To Group
Here is my Table Structure ( from Oracle database)
Team  |  Customer Code  | Amount   | Credit Limit
1 , a, 100, 1000
1 , a , 200, 1000
1 , b, 100, 100
1, b, 1000, 100
1, b, 2000, 100
2, a, 100, 2000


For the Report, I want to group the Team and  Sum each customer total Amount and Show the Exceed limit amount.
Here I want to present
Team    Customer Code   Amount   Credit Limit   Exceed
1               a                      300          1000           0
1                b                   3100          100            3000
Team Total                     3300                           3000
2               a                      100           2000          0
Team Total                      100                            0 
Total                                3400                          3000 

BUT it turn out..
Team    Customer Code   Amount   Credit Limit   Exceed
1               a                      300          1000           0
1                b                   3100          100            3000
Team Total                     3300                          2300 ( Problem here a  )
2               a                      100           2000          0
Team Total                      100                            0  ( Problem here a )
Total                                3400                          2400 ( Problem here b)


I Grouped the Custoer Code and Team I can preform the sum
however I can't Do the Exceed total
becoz the value should be
iif (Sum(amount)>(Creditlimt) , Sum(amount)-First(Creditlimt), 0)
but  for the team total in team 1 the result is 2300 ( 3300 - customer a 's limit) not add from exceed amount
And the finial total it turns out 2400 (3400 - 1000)

I have tried use the coding to sum up the exceed
but I found that the group total is sumup first than the sum up the detail :

Team    Customer Code   Amount   Credit Limit   Exceed
1               a                      300          1000           0
1                b                   3100          100            3000
Team Total                     3300                          0
2               a                      100           2000          0
Team Total                      100                           3000  ( The Total from Team 1 ! )
Total                                3400                       0 ( Problem here b)


this situration , I can't change the query statement
I can do the good result for CR report
but for reporting service 2005, I can't to the first report result
Any one can help me ??
thank you

View Replies !
Service Broker Not Working For Restored Databases (SQL 2000 Databases Restored On 2005)
I just restored my SQL server 2000 database on the SQL server 2005. after this i ran the Service broker sample ("Hello World") on this database by changing the AdventureWorks name to the new database name. The "setup.sql" runs fine. When i run the "SendMessage.sql" i was not getting any rows in the output (The message was not getting inserted into the queue). I checked the Service broker is enabled on this databased using the query "select is_broker_enabled from sys.databases where name = 'newdbname' " It was 1. I even tried the ALTER DATABASE SET ENABLE_BROKER. but it didnt work.

When i tried the sample on a newly created database it worked fine.

Is there any solution to make the restored database to work for service broker.

Thanks

Prashanth

View Replies !
Comp.databases , Comp.databases.theory , Comp.databases.ms-sqlserver
Are there any tools to have the primary conversion of ISAM databasestructure to SQLServer [relational]?Thanks.- Kedar Agarkar

View Replies !
Name Split
Quick question.

I've got a CHAR (70) field called NAME that has a first and last name separated by a space. I want to split it into two fields FIRST and LAST -- with all the characters to the left of the space a first name and all the characters to the right of the space as last name. I couldn't find a string function that would let me do this simply (it may be right in front of me and I missed it).

Thanks in advance.

Ray

View Replies !
Name Split
I need to split a column of Full Names into First name and Last name columns. Has someone come across this before and if so can you give me an idea of how to overcome it?

View Replies !
Split Value In Sql
Hi to all

I have one problem regarding sp and pass value in sp
I am gating a value like Abc,Def,Ghi,

Now I want to split the whole pass value by “,�
And fire one for loop to store value in database
This things is done in asp.net web form but I want to do all process in sp
So please guide me how I am write sp .
The purpose is pass value one time so connection time is decrees and give fast perforce

View Replies !
To Split Or Not To Split
I have a database with a "large" table containing date based information Basically they're reservations. I've thought about creating a new table and adding any records from past years to this table. For the most part only current reservation need to be searchable, but in some circumstances it would be useful to be able to search through the archive too. so, my questions!!!

Is 8,000 or so rows of data "large" and unwieldly in SQL terms?

Would splitting this data into 2 tables - one small table for current and future reservations and one larger archive table then using a UNION SELECT query to make archive information seachable be a significant improvment on server resources/load or am I making the whole thing more complicated than it need be as 8,000 rows of data is nothing to worry about.............

What did they say about a little bit of knowledge being a dangerous thing?

Thanks in advance of any guidance to a neophyte!!?

View Replies !
SPLIT() UDF
SQL UDF split()

The objective of this article is to help the SQL developers with an UDF that can be used within a stored procedures or Function to split a string (based on given delimiter) and extract the required portion of the string.

Scripting languages like VB script and Java script have in-built split() functions but there is no such function available in SQL server. In my experience this function is really handy when you’re working on an ASP application with SQL server as backend, whereby you’ll need to pass the ASP page submitted values to the SQL stored procedure.

To give a simple example, in a typical Monthly reporting ASP page – the users would select a range of months and extract the information pertaining to this date range. Classic implementation of this model is to have an ASP page to accept the input parameters and pass the values to the SQL stored procedure (SP). The SP would return a result set which is then formatted in the ASP page as results.

If the date range is continuous ie. JAN07 to MAR07 then the SP can typically accept a ‘From’ and ‘To’ range variables. But I’ve encountered situations whereby the users select 3 months from the current year and 2 months from previous year (non-continuous date ranges). In such scenario the SP cannot have a date range as input parameters.

Typically an ASP programmer would do is by having a single date input parameter in the SP and call the SP within a loop in the ASP page. This is an inefficient way of programming as contacting the database server within an ASP loop could cause performance overhead especially if the table being queried is an online transaction processing table.

Here is how I handled the above situation.

1.Declared one string input parameter of type varchar(8000) (if you’re using SQL 2005 then it is advisable to use Varchar(Max))
2.Pass the ASP submitted values as string, in this case the months selected by user would be supplied to the SP as a string
3.Within the Stored Procedure I’ll call the split() function to extract each month from the string and query the corresponding data

The basic structure of the stored procedure is as pasted below:-

CREATE PROCEDURE FETCH_SALES_DETAIL (
@MONTH VARCHAR(MAX)
)
AS
BEGIN
DECLARE @MONTH_CNT INT,@MTH DATETIME
SET @MONTH_CNT=1
WHILE DBO.SPLIT(@MONTH,',',@MONTH_CNT) <> ''
BEGIN
SET @MTH = CAST(DBO.SPLIT(@MONTH,',',@MONTH_CNT) AS DATETIME)
--<<Application specific T-SQLs>>-- (BEGIN)
SELECT [SALES_MONTH],[SALES_QTY],[PRODUCT_ID],[TRANSACTION_DATE]
FROM SALES (NLOCK)
WHERE [SALES_MONTH]= @MTH
--<<Application specific T-SQLs>>--(END)

SET @MONTH_CNT=@MONTH_CNT+1
END
END

Dbo.SPLIT() function takes 3 parameters
1)The main string with the values to be split
2)The delimiter
3)The Nth occurrence of the string to be returned

The functionality of the UDF is as explained STEP by STEP:

1.Function Declaration
CREATE FUNCTION [dbo].[SPLIT]
(
@nstring VARCHAR(MAX),
@deliminator nvarchar(10),
@index int
)

RETURNS VARCHAR(MAX)

Function is declared with 3 input parameters:-
@nstring of type VARCHAR(MAX) will hold the main string to be split
@deliminator of type NVARCHAR(10) will hold the delimiter
@index of type INT will hold the index of the string to be returned
2.Variable Declaration
DECLARE @position int
DECLARE @ustr VARCHAR(MAX)
DECLARE @pcnt int

Three variables are needed within the function. @position is an integer variable that will be used to traverse along the main string. @ustr will store the string to be returned and the @pcnt integer variable to check the index of the delimiter.
3.Variable initialization
SET @position = 1
SET @pcnt = 1
SELECT @ustr = ''
Initialize the variables
4.Main functionality
WHILE @position <= DATALENGTH(@nstring) and @pcnt <= @index
BEGIN
IF SUBSTRING(@nstring, @position, 1) <> @deliminator BEGIN
IF @pcnt = @index BEGIN
SET @ustr = @ustr + CAST(SUBSTRING(@nstring, @position, 1) AS nvarchar)
END
SET @position = @position + 1
END
ELSE BEGIN
SET @position = @position + 1
SET @pcnt = @pcnt + 1
END
END

4.1The main while loop is used to traverse through the main string until the word index is less than or equal to the index passed as input parameter.
4.2Within the while loop each character within the string is verified against the delimiter and if it does not match then local word count variable is checked against the input index parameter
4.3If the values are same ie., the input variable index and the word being processed in the while loop are the same then the word is stored in the @ustr variable. If the values does not match then the @position variable is incremented.
4.4If the character matches with the delimiter then the word count variable @pcnt is incremented along with the @position variable

5.Return the value
RETURN @ustr

I hope this article would benefit those who are looking for a handy function to deal with Strings.

Feel free to send your feedback at dearhari@gmail.com

View Replies !
How To Split A String Using Sql
I have 5 dynamic rows each row consisting of 5 checkboxes & 5 dropdowns.I am concatenating the values of each controls in a row using a wildcard charater "~" and each row i am concatenating using "|".The complete string is then assigned to one hidden field and passed as sql parameter to the backend.

Please help in writing the split function to get the values of each checkboxes and dropdowns from the string in order to save them in separate columns.

Thanks

View Replies !
SQL Search Split
CREATE PROCEDURE [dbo].[ShowComboLocation]@Keyword varchar(50) ASSELECT TOP 100 PERCENT PropertyAreaID, PropertyAreaFROM dbo.iViewAllWHERE (PropertyArea LIKE '%' + @Keyword + '%')GOQuestion 1 isIf Keyword ="London WestEnd Harrods", I know my query will end up like this (PropertyArea LIKE 'London WestEnd Harrods')But I want to to individually search for 3 or 1-nth words therefore my query should end up like this(PropertyArea LIKE 'London')OR (PropertyArea LIKE 'WestEnd')OR (PropertyArea LIKE 'Harrods')i WANT TO perform this on my SQL STored Procedure,Can anybody provide code or links pls

View Replies !
Reg Split Funtion
Hi,

Is it possible to split the following value in sql server ?

I have the value like 25 Email Accounts,50 Email Accounts in my sqlserver database.
Here i need only the numeric value .ie 25,50.Is it possible? can any one give me the solution ..

I am using ASP.Net and C# backend is SQL Server 2000.

Thanks and Regards
Arul

View Replies !
Split A Field
Whats the best way to do the following?Field1 in Table1 contains numbers and characters seperated by #Examples: aaa#01, kjhkjhjh#21 and jlkjlkj#123How can I create two new fields in Table1, one containing what is tothe left of the # and the other what is to the right?Regards,Ciarán

View Replies !
Split A Column
Hi everybody

Does any body know how to split a field in a table into two fields

eg
usermaster(table)
userid(field)

usermaster has 40 users with user id 1 to 40
i want to get data as

userid userid
1 21
2 22
3 23
. .
. .
. .
20 40

Thanks you very much

View Replies !
Split Tables And Keep ID
I have a large table that I'm planning on splitting out into 5 smaller ones. What I need to do is maintain some central repository for auto-numbering new records to make sure that no 2 records in different tables have the same unique ID. Thanks in advance!

View Replies !
Split A String
Hi
I have this string which might have a hyphen in it "-"
What I want to do is
if I get a hyphen then take all characters after hyphen
else take only all the characters starting from the 5th position of the string
How can this be achieved?

View Replies !
Split A String In Sql
Hi I need a stored procedure in SQL that will split a comma separated variable passed to it
select a name for each value and return a recordset. Any pointers greatfully received.
First attempt is dreadfully slow as I am opening recordsets each time

Function func_getFood()
Dim rsfoodsql
Dim foodoutput
for x=1 to ubound(masterfoodarray)-2
set rsfoodsql= objconn.execute ("select foodname from tbl"&language&"food where foodID='"& masterfoodarray(x) &"'")
if not rsfoodsql.eof then
foodoutput=rsfoodsql("foodname")
if not foodoutput="" then
response.write foodoutput&"<BR>"
end if
end if
next
End Function

Hope someone can help,
cheers

View Replies !
Should I Split The Procedure Or Not???
I have a procedure that is going to be called through asp pages. This procedure carries out instructions depending on whether customers wants to insert, update or delete their portfolios. Rules are as follows: 1. It should not allow duplicate portfolio name to insert. 2. If customer has reached their max limit of 20 portfolio they can't add. They may have to delete or update the existing portfolio first. 3. all the error handling is done and returned as output parameters.

Now coming to the question at present I have one procedure that does all these things. Should I split up the procedure and have three procedures handling the events seperately: 1 Insert 2 Delete 3 update The reason I am concerned is 1 procedure being hit so many times by concurrent users with varying events. I am concerned about performance issue and slowing down of the page. I do not have exact numbers of users at this point. But they would be in thousands or more. Thanks for any suggestions or advice you all might have to share. Hiku

View Replies !
Split A Fullname
I want to know how to parse a fullname into a fname and lname.

View Replies !
Split Relationship ?
What I have is a table with a primary key. Then I have 5 other tables with a relating key. No problems there.

I need to create a relationship with the primary table (primary) key who's data field is 25 charachters. I need to parse that out and have 3 charachters go to one, 2 to the other and so on.

I don't know how to do that, can you help?

View Replies !
Split Pipeline
 

This is probably obvious, but how do I split a pipeline. I.e. I've got a data source with 200 columns - I need to split this into 20 pipelines each containing 10 of the original columns.

View Replies !
Split The File
my ssis package downloades the text file from Ftp. iT downloades for ex 5 files.

I want to split the file to smaller file after downloades. If the size of file is more then 600 mB then I want to split it into 6 files.

please suggest if any task in SSIS can perform this or any other way.

 

View Replies !
Tell To Split On Change Of ID
how can I tell the conditional component to split the records based on change of hdr_HeaderID

http://www.webfound.net/split_on_headerid.jpg

let me know if you need more info...

 

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved