Usage of sequence in SQL Server 2012 - sql-server

I have SQL Server 2012 and I want to know what's the usage of sequence. I Look for a sample to explain usage of sequence.
EDIT
I know create and use Sequence in database. I want to know what is practical scenario for use of Sequence.

CREATE SEQUENCE dbo.OrderIDs
AS INT
MINVALUE 1
NO MAXVALUE
START WITH 1;
SELECT NextOrderID = NEXT VALUE FOR dbo.OrderIDs
UNION ALL SELECT NEXT VALUE FOR dbo.OrderIDs
UNION ALL SELECT NEXT VALUE FOR dbo.OrderIDs;
Results:
NextOrderID
-----------
1
2
3
See here for original source and more examples. The page refers to SQL Server Denali which is the beta of SQL 2012 but the syntax is still the same.

One of the ways I leverage the SEQUENCE command is for reference numbers in an ASP/C# detailsview page (as an example). I use the detailsview to enter requests into a database and the SEQUENCE command serves as the request/ticket number for each request. I set the inital sequence command to start with a specific number and increment by 1 for each request.
If I present these requests in a gridview I make the SEQUENCE reference numbers appear but don't make them editable. Its great for a reference number when records are similar with other fields in the database. It's also perfect for customers when they have questions about a specific entry in a given database. This way I have a unique number per entry no matter if the rest of the information is identical or not.
Here's how I generally leverage the SEQUENCE command:
CREATE SEQUENCE blah.deblah
START WITH 1
INCREMENT BY 1
NO CYCLE
NO CACHE
In short, I start my sequence at #1 (you can choose any number you want to start with) and it counts upwards in increments of 1. I don't cycle the sequence numbers when they reach the system max number.

Related

Ssrs reports Windows 2008

I'm fairly new to SQL and I have been issued my first report to build. I have written an SQL query to give me a set of results that I would like to publish in a report.
I have unioned about 20 small queries all containing the correct amount of columns. One column is a misc column with about 15 different descriptions in (this is what I want to count).
I have uploaded my data set and now want to be able to choose a cell in my report to bring back a certain description.
At the minute I'm using
=count(fields!misc.values)
and it's giving me the whole count, about 200.
I would like to know if there is any kind of "where clause" (filter) which I can use to state which description results I want to bring back.
You can use am expression to count the misc.value you need. It will work like a count using a where clause:
=Sum(iif(Fields!misc.Value ="Some description",1,0))
Example:
For count the FSMethod with MethodOne as value I used this expression:
=Sum(iif(Fields!FSMethod.Value ="MethodOne",1,0))
Note the expression sums by 1 if the FSMethod.Value is MethodOne.
For count the rows with FSMethod column with MethodTwo value.
=Sum(iif(Fields!FSMethod.Value ="MethodTwo",1,0))
Let me know if this can help you.

SSIS Export all data from one table into multiple files

I have a table called customers which contains around 1,000,000 records. I need to transfer all the records to 8 different flat files which increment the number in the filename e.g cust01, cust02, cust03, cust04 etc.
I've been told this can be done using a for loop in SSIS. Please can someone give me a guide to help me accomplish this.
The logic behind this should be something like "count number of rows", "divide by 8", "export that amount of rows to each of the 8 files".
To me, it will be more complex to create a package that loops through and calculates the amount of data and then queries the top N segments or whatever.
Instead, I'd just create a package with 9 total connection managers. One to your Data Database (Source) and then 8 identical Flat File Connection managers but using the patterns of FileName1, Filename2 etc. After defining the first FFCM, just copy, paste and edit the actual file name.
Drag a Data Flow Task onto your Control Flow and wire it up as an OLE/ADO/ODBC source. Use a query, don't select the table as you'll need something to partition the data on. I'm assuming your underlying RDBMS supports the concept of a ROW_NUMBER() function. Your source query will be
SELECT
MT.*
, (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) % 8 AS bucket
FROM
MyTable AS MT;
That query will pull back all of your data plus assign a monotonically increasing number from 1 to ROWCOUNT which we will then apply the modulo (remainder after dividing) operator to. By modding the generated value by 8 guarantees us that we will only get values from 0 to 7, endpoints inclusive.
You might start to get twitchy about the different number bases (base 0, base 1) being used here, I know I am.
Connect your source to a Conditional Split. Use the bucket column to segment your data into different streams. I would propose that you map bucket 1 to File 1, bucket 2 to File 2... finally with bucket 0 to file 8. That way, instead of everything being a stair step off, I only have to deal with end point alignment.
Connect each stream to a Flat File Destination and boom goes the dynamite.
You could create a rownumber with a Script Component (don't worry very easy): http://microsoft-ssis.blogspot.com/2010/01/create-row-id.html
or you could use a rownumber component like http://microsoft-ssis.blogspot.com/2012/03/custom-ssis-component-rownumber.html or http://www.sqlis.com/post/Row-Number-Transformation.aspx
For dividing it in 8 files you could use the Balanced Data Distributor or the Conditional Split with a modulo expression (using your new rownumber column):

SPSS :Loop through the values of variable

I have a dataset that has patient data according to the site they visited our mobile clinic. I have now written up a series of commands such as freqs and crosstabs to produce the analyses I need, however I would like this to be done for patients at each site, rather than the dataset as whole.
If I had only one site, a mere filter command with the variable that specifies a patient's site would suffice, but alas I have 19 sites, so I would like to find a way to loop through my code to produce these outputs for each site. That is to say for i in 1 to 19:
1. Take the i th site
2. Compute a filter for this i th site
3. Run the tables using this filtered data of patients at ith site
Here is my first attempt using DO REPEA. I also tried using LOOP earler.
However it does not work I keep getting an error even though these are closed loops.
Is there a way to do this in SPSS syntax? Bear in mind I do not know Python well enough to do this using that plugin.
*LOOP #ind= 1 TO 19 BY 1.
DO REPEAT #ind= 1 TO 20.
****8888888888888888888888888888888888888888888888888888888 Select the Site here.
COMPUTE filter_site=(RCDSITE=#ind).
USE ALL.
FILTER BY filter_site.
**********************Step 3: Apply the necessary code for tables
*********Participation in the wellness screening, we actually do not care about those who did FP as we are not reporting it.
COUNT BIO= CheckB (1).
* COUNT FPS=CheckF(1).
* COUNT BnF= CheckB CheckF(1).
VAL LABEL BIO
1 ' Has the Wellness screening'
0 'Does not have the wellness screening'.
*VAL LABEL FPS
1 'Has the First patient survey'.
* VAL LABEL BnF
1 'Has either Wellness or FPS'
2 'Has both surveys done'.
FREQ BIO.
*************************Use simple math to calcuate those who only did the Wellness/First Patient survey FUB= F+B -FnB.
*******************************************************Executive Summary.
***********Blood Pressure.
FREQ BP.
*******************BMI.
FREQ BMI.
******************Waist Circumference.
FREQ OBESITY.
******************Glucose.
FREQ GLUCOSE.
*******************Cholesterol.
FREQ TC.
************************ Heamoglobin.
FREQ HAEMOGLOBIN.
*********************HIV.
FREQ HIV.
******************************************************************************I Lifestyle and General Health.
MISSING VALUES Gender GroupDep B8 to B13 ('').
******************Graphs 3.1
Is this just Frequencies you are producing? Try the SPLIT procedure by the variable RCDSITE. Should be enough.
SPLIT FILES allows you to partition your data by up to eight variables. Then each procedure will automatically iterate over each group.
If you need to group the results at a higher level than the procedure, that is, to run a bunch of procedures for each group before moving on to the next one so that all the output for a group will be together, you can use the SPSSINC SPLIT DATASET and SPSSINC PROCESS files extension commands to do this.
These commands require the Python Essentials. That and the commands can be downloaded from the SPSS Community website (www.ibm.com/developerworks/spssdevcentral) if you have at least version 18.
HTH,
Jon Peck
A simple but perhaps not very elegant way is to select from the menu: Data/Select Cases/If condition, there you enter the filter for site 1 and press Paste, not OK.
This will give the used filter as syntax code.
So with some copy/paste/replace/repeat you can get the freqs and all other results based on the different sites.

Increment a row in SQL Server database after the LAST row within a range

I have tried looking for an answer for my question but due to lack of proper knowledge in databases, I thought some genius here could help me out.
I'm trying to add rows into a database table starting from the number 800 and onwards in a sequential order. The database currently has records from 1 up until 300.
This record in the table is not automatically incremented, but assigned manually.
I basically want to start another batch of numbers, but rather than incrementing them from where the program left off (i.e. from 300) I would like to start them from 800.
I tried different SQL statements but got nothing concrete to go with. I'm using PHP to enter these rows.
I feel like this shouldn't be so hard but I'm a novice and it kills!
I thought maybe adding one record that starts from 800 and then executing a statement like
SELECT LAST FROM A RANGE BETWEEN 800 AND 899
would be the way to go.
Any help, advice?
You can obtain the highest numbered record with the MAX aggregate function. The following will find the next highest number that is between 800 and 899.
SELECT MAX(my_assigned_number) + 1 as next_number
FROM my_table
WHERE my_assigned_number > 800 AND my_assigned_number < 899;

How do I get around the Sum(First(...)) not allowed limitation is SSRS2005

The problem that I have is SQL Server Reporting Services does not like Sum(First()) notation. It will only allow either Sum() or First().
The Context
I am creating a reconciliation report. ie. what sock we had a the start of a period, what was ordered and what stock we had at the end.
Dataset returns something like
Type,Product,Customer,Stock at Start(SAS), Ordered Qty, Stock At End (SAE)
Export,1,1,100,5,90
Export,1,2,100,5,90
Domestic,2,1,200,10,150
Domestic,2,2,200,20,150
Domestic,2,3,200,30,150
I group by Type, then Product and list the customers that bought that product.
I want to display the total for SAS, Ordered Qty, and SAE but if I do a Sum on the SAS or SAE I get a value of 200 and 600 for Product 1 and 2 respectively when it should have been 100 and 200 respectively.
I thought that i could do a Sum(First()) But SSRS complains that I can not have an aggregate within an aggregate.
Ideally SSRS needs a Sum(Distinct())
Solutions So Far
1. Don't show the Stock at Start and Stock At End as part of the totals.
2. Write some code directly in the report to do the calc. tried this one - didn't work as I expected.
3. Write an assembly to do the calculation. (Have not tried this one)
Edit - Problem clarification
The problem stems from the fact that this is actually two reports merged into one (as I see it). A Production Report and a sales report.
The report tried to address these criteria
the market that we sold it to (export, domestic)
how much did we have in stock,
how much was produced,
how much was sold,
who did we sell it to,
how much do we have left over.
The complicating factor is the who did we sell it to. with out that, it would have been relativly easy. But including it means that the other top line figures (stock at start and stock at end) have nothing to do with the what is sold, other than the particular product.
I had a similar issue and ended up using ROW_NUMBER in my query to provide a integer for the row value and then using SUM(IIF(myRowNumber = 1, myValue, 0)).
I'll edit this when I get to work and provide more data, but thought this might be enough to get you started. I'm curious about Adolf's solution too.
Pooh! Where's my peg?!
Have you thought about using windowing/ranking functions in the SQL for this?
This allows you to aggregate data without losing detail
e.g. Imagine for a range of values, you want the Min and Max returning, but you also wish to return the initial data (no summary of data).
Group Value Min Max
A 3 2 9
A 7 2 9
A 9 2 9
A 2 2 9
B 5 5 7
B 7 5 7
C etc..
Syntax looks odd but its just
AggregateFunctionYouWant OVER (WhatYouWantItGroupedBy, WhatYouWantItOrderedBy) as AggVal
Windowing
Ranking
you're dataset is a little weird but i think i understand where you're going.
try making the dataset return in this order:
Type, Product, SAS, SAE, Customer, Ordered Qty
what i would do is create a report with a table control. i would set up the type, product, and customer as three separate groups. i would put the sas and sae data on the same group as the product, and the quantity on the customer group. this should resemble what i believe you are trying to go for. your sas and sae should be in a first()
Write a subquery.
Ideally SSRS needs a Sum(Distinct())
Re-write your query to do this correctly.
I suspect your problem is that you're written a query that gets you the wrong results, or you have poorly designed tables. Without knowing more about what you're trying to do, I can't tell you how to fix it, but it has a bad "smell".

Resources