Search

Wednesday, 25 May 2011

How to Share Data Between Stored Procedures


How to Share Data Between Stored Procedures
http://www.sommarskog.se/share_data.html


  • Using OUTPUT Parameters
  • Table-valued User-defined Functions
  • Using a Table
  • Insert-Exec
  • Table Parameters, and Table Types
  • Using the CLR
  • OPENQUERY
  • Using XML
  • Using Cursor Variables

    A must read.
  • SELECT @@spid

    SELECT @@spid
    

    Using @@SPID to return the SessionID of the T-SQL session that the statements are currently in.

    HTML PRE Tag

    Definition and Usage


    The PRE tag defines preformatted text.

    Text in a PRE element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.

    Monday, 23 May 2011

    Using CROSS APPLY (t-sql)

    Using CROSS APPLY (t-sql)
    Given:

    CREATE FUNCTION dbo.fn_GetTopOrders(@custid AS int, @n AS INT)
    RETURNS TABLE
    AS
    RETURN
    SELECT TOP(@n) *
    FROM Sales.SalesOrderHeader
    WHERE CustomerID = @custid
    ORDER BY TotalDue DESC
    GO

    which returns the top n orders per customerID



    SELECT C.CustomerID,
    O.SalesOrderID,
    O.TotalDue
    FROM
    AdventureWorks.Sales.Customer AS C
    CROSS APPLY
    AdventureWorks.dbo.fn_GetTopOrders(C.CustomerID, 3) AS O
    ORDER BY
    CustomerID ASC, TotalDue DESC


    results in this...



    CustomerID SalesOrderID TotalDue
    ----------- ------------ ---------------------
    1 45283 37643.1378
    1 46042 34722.9906
    1 44501 26128.8674
    2 46976 10184.0774
    2 47997 5469.5941
    2 57044 4537.8484
    3 53616 92196.9738
    3 47439 78578.9054
    3 48378 56574.3871
    4 47658 132199.8023
    . . .




    The APPLY clause acts like a JOIN without the ON clause comes in two flavors: CROSS and OUTER.
    The OUTER APPLY clause returns all the rows on the left side (Customers)
    whether they return any rows in the table-valued-function or not (the "LEFT JOIN" table).

    The columns that the table-valued-function returns are null if no rows are returned.

    The CROSS APPLY only returns rows from the left side (Customers)
    if the table-valued-function returns rows.

    Notice that I'm just passing in the CustomerID to the function.
    It returns the TOP 3 rows based on the amount of the order.

    Since I'm using CROSS APPLY a customer without orders won't appear in the list.
    I can also pass in a number other than 3 to easily return a different number of orders per customer.

    Even better I can pass in a different number of orders for each customer.
    So I could list the top 5 orders for one type of customer but the top 10 for another type of customer.

    How cool is that?!?

    And it gets even better.
    Remember the function has an ORDER BY in it.
    It will always return the top orders based on the amount.
    However you can change the ORDER BY clause in the query that calls the function to display those rows in whatever order you want.
    You could easily display the top 3 orders in ascending order instead.

    [SQL] @@Identity, SCOPE_IDENTITY

    [SQL] @@Identity, SCOPE_IDENTITY()
    msdn link


    SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions because they return values that are inserted into identity columns.

    IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT (Transact-SQL).

    SCOPE_IDENTITY and @@IDENTITY return the last identity values that are generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.

    For example, there are two tables, T1 and T2, and an INSERT trigger is defined on T1. When a row is inserted to T1, the trigger fires and inserts a row in T2. This scenario illustrates two scopes: the insert on T1, and the insert on T2 by the trigger.

    Assuming that both T1 and T2 have identity columns, @@IDENTITY and SCOPE_IDENTITY will return different values at the end of an INSERT statement on T1. @@IDENTITY will return the last identity column value inserted across any scope in the current session. This is the value inserted in T2. SCOPE_IDENTITY() will return the IDENTITY value inserted in T1. This was the last insert that occurred in the same scope. The SCOPE_IDENTITY() function will return the null value if the function is invoked before any INSERT statements into an identity column occur in the scope.

    Failed statements and transactions can change the current identity for a table and create gaps in the identity column values. The identity value is never rolled back even though the transaction that tried to insert the value into the table is not committed. For example, if an INSERT statement fails because of an IGNORE_DUP_KEY violation, the current identity value for the table is still incremented.

    Thursday, 19 May 2011

    SQL Server Logins and Users

    Gleamed from akadia.com

    SQL Server Logins and Users
    Overview
    Although the terms login and user are often used interchangeably, they are very different.
  • A login is used for user authentication
  • A database user account is used for database access and permissions validation.

    Logins are associated to users by the security identifier (SID).
    A login is required for access to the SQL Server server. The process of verifying that a particular login is valid is called "authentication". This login must be associated to a SQL Server database user. You use the user account to control activities performed in the database. If no user account exists in a database for a specific login, the user that is using that login cannot access the database even though the user may be able to connect to SQL Server. The single exception to this situation is when the database contains the "guest" user account. A login that does not have an associated user account is mapped to the guest user. Conversely, if a database user exists but there is no login associated, the user is not able to log into SQL Server server.



    When a database is restored to a different server it contains a set of users and permissions but there may not be any corresponding logins or the logins may not be associated with the same users. This condition is known as having "orphaned users."

    Troubleshooting Orphaned Users
    When you restore a database backup to another server, you may experience a problem with orphaned users. The following scenario illustrates the problem and shows how to resolve it.
    Use master
    sp_addlogin 'test', 'password', 'Northwind'

    SELECT sid FROM dbo.sysxlogins WHERE name = 'test'

    0xE5EFF2DB1688C246855B013148882E75
    Grant access to the user you just created
    Use Northwind
    sp_grantdbaccess 'test'
    SELECT sid FROM dbo.sysusers WHERE name = 'test'

    0xE5EFF2DB1688C246855B013148882E75

    As you can see, both SID's are identical.

    Backup the database
    Use master
    BACKUP DATABASE Northwind
    TO DISK = 'C:\Northwind.bak'

    Copy the Backupfile to another Maschine and SQL Server and restore it as follows:
    RESTORE FILELISTONLY
    FROM DISK = 'C:\Users\Zahn\Work\Northwind.bak'

    Northwind
    Northwind_log


    RESTORE DATABASE TestDB
    FROM DISK = 'C:\Users\Zahn\Work\Northwind.bak'
    WITH
     MOVE 'Northwind' TO 'D:\DataMSSQL\Data\northwnd.mdf',
     MOVE 'Northwind_log' TO 'D:\DataMSSQL\Data\northwnd.ldf'

    The restored database contains a user named "test" without a corresponding login, which results in "test" being orphaned.

    Check the SID's
    Use master
    SELECT sid FROM dbo.sysxlogins WHERE name = 'test'

    0x39EE98D37EAC2243B7833705EC1C60E3

    Use TestDB
    SELECT sid FROM dbo.sysusers WHERE name ='test'

    0xE5EFF2DB1688C246855B013148882E75

    Now, to detect orphaned users, run this code
    Use TestDB
    sp_change_users_login 'report'

    test 0xE5EFF2DB1688C246855B013148882E75

    The output lists all the logins, which have a mismatch between the entries in the sysusers system table, of the TestDB database, and the sysxlogins system table in the master database.

    Resolve Orphaned Users

    Use TestDB
    sp_change_users_login 'update_one', 'test', 'test'


    SELECT sid FROM dbo.sysusers WHERE name = 'test'
    0x39EE98D37EAC2243B7833705EC1C60E3

    use master
    SELECT sid FROM dbo.sysxlogins WHERE name ='test'

    0x39EE98D37EAC2243B7833705EC1C60E3

    This relinks the server login "test" with the the TestDB database user "test".
    The sp_change_users_login stored procedure can also perform an update of all orphaned users with the "auto_fix" parameter but this is not recommended because SQL Server attempts to match logins and users by name.
    For most cases this works; however, if the wrong login is associated with a user, a user may have incorrect permissions.
  • SQL SERVER SET TRANSACTION ISOLATION LEVEL

    Gleamed from MSDN library

    SET TRANSACTION ISOLATION LEVEL

    SQL Server 2000 Controls the default transaction locking behavior for all Microsoft® SQL Server™ SELECT statements issued by a connection.

    Syntax
    SET TRANSACTION ISOLATION LEVEL
    { READ COMMITTED
    | READ UNCOMMITTED
    | REPEATABLE READ
    | SERIALIZABLE
    }

    Arguments
  • READ COMMITTED
    Specifies that shared locks are held while the data is being read to avoid dirty reads, but the data can be changed before the end of the transaction, resulting in nonrepeatable reads or phantom data. This option is the SQL Server default.

  • READ UNCOMMITTED
    Implements dirty read, or isolation level 0 locking, which means that no shared locks are issued and no exclusive locks are honored. When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. This option has the same effect as setting NOLOCK on all tables in all SELECT statements in a transaction. This is the least restrictive of the four isolation levels.

  • REPEATABLE READ
    Locks are placed on all data that is used in a query, preventing other users from updating the data, but new phantom rows can be inserted into the data set by another user and are included in later reads in the current transaction. Because concurrency is lower than the default isolation level, use this option only when necessary.

  • SERIALIZABLE
    Places a range lock on the data set, preventing other users from updating or inserting rows into the data set until the transaction is complete. This is the most restrictive of the four isolation levels. Because concurrency is lower, use this option only when necessary. This option has the same effect as setting HOLDLOCK on all tables in all SELECT statements in a transaction.

    Remarks
    Only one of the options can be set at a time, and it remains set for that connection until it is explicitly changed. This becomes the default behavior unless an optimization option is specified at the table level in the FROM clause of the statement.

    The setting of SET TRANSACTION ISOLATION LEVEL is set at execute or run time and not at parse time.

    Examples
    This example sets the TRANSACTION ISOLATION LEVEL for the session. For each Transact-SQL statement that follows, SQL Server holds all of the shared locks until the end of the transaction.

    SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
    GO
    BEGIN TRANSACTION
    SELECT * FROM publishers
    SELECT * FROM authors
    ...
    COMMIT TRANSACTION
  • Tuesday, 26 April 2011

    How to Create a Custom Windows Installation DVD or USB Install

    Article lifted from LifeHacker.


    http://lifehacker.com/?utm_source=Lifehacker+Newsletter&utm_campaign=c3be0c41d7-UA-142218-1&utm_medium=email#!5793427/how-to-create-a-custom-windows-installation-dvd-or-usb-install


  • rt7lite

    If you're looking to integrate Windows 7's Service Pack into your disc, you'll want to scroll down to the beta releases. That service pack includes all the patches, security fixes, and other updates from its first year and a half of existence, so I'd recommend snagging the beta. Download the appropriate 32-bit or 64-bit dowload for your system (the system you're working on, not the Windows disc you intend to create), install RT7Lite, and launch it.

    The beta release for RT7Lite that includes Windows 7 with SP1 is :
    Download RT Se7en Lite - Beta (build 2.6.0) for windows 7, windows Vista x64 now!
    http://www.pub.rt7lite.com/7lite-rc-beta-1726-dec6-10-stable/rt_7_lite_win7_Vista_x64_sp1.exe



  • http://sourceforge.net/projects/unetbootin/files/UNetbootin/Custom/unetbootin-eeeubuntu-windows-276.exe/download

    http://www.tomshardware.co.uk/forum/243423-14-image-flash

    UPDATE - still having issues with usb installation - resorting to:

    http://www.intowindows.com/how-to-install-windows-7vista-from-usb-drive-detailed-100-working-guide/


    xcopy c:\ d:\ /h/i/c/k/e/r/y

  • Friday, 22 April 2011

    Reset SERVICE indicator on VAG cars

    From my SKODA service Manual

    Models with FIXED SERVICE INTERVALS (QG0)

    1. Switch off the ignition, press the reset button of the trip counter for distance driven, and hold it down.
      Switching the ignition on causes a service interval to appear on the display.
    2. Holding the reset button down for 10 seconds will cause the counter to be reset (the display shows "---" and then the trip counter readout).

      The readout "OIL" will appear in the display after resetting the indicator "INSP", and releasing the reset button when both service intervals (INSP and OIL) were reached together.

    3. Repress the reset button and hold it down for 10 seconds to also reset this interval

       

    Models with EXTENDED SERVICE INTERVALS (QG1 and QG2)

    1. Switch off the ignition, press the reset button of the trip counter for "distance driven" and hold it down.
    2. Switch the ignition ON, and release the reset button.
    3. Now turn the reset button to the RIGHT.

       

      All counters will be reset to 0.

    Tuesday, 19 April 2011

    Car – check your engine oil via Castrol.com

    Castol's "What's the right oil for my car?"

    The CASTROL.COM website, has a handy function that lets you check what specification oil is ideal or recommended for your motor.





    My Skoda Fabia vRS needs the following VW PD 505.01 or higher CASTROL oil specification (Castol EDGE)




    The various Castrol Magnatec oil range details can be found here.

    Monday, 14 March 2011

    PD Engine Oil details, and a funny EuroCarParts site error...

    It's that time of year again, where I have to get the service parts in – usually from EuroCarParts, and Ebay.

     

    To my surprise, when I was looking for some PD (Pumpe-Düse) engine oil, EuroCarParts had a site error (well, that's what I hope it is...)


     

    Yep – that's right, £1,993.48.

     

    Cheap as Chips.

     

    Anyway – onto something more relevant.

    The specification of oil needed for various PD engines, has been politely referred to in a forum thread on the ever helpful SeatCupra.net.

    The link to the thread is here.

     

    However – to summaries:

    TD / SDI / TDI diesel

    505 00 / 505 01 / 506 01/ 507 00

    TDI P.D.:

    505 01 / 506 01 / 507 00

    TDI-PD (1.9l BPX and BUK) diesel

    506 01 / 507 00

    TDI with particle filter

    507 00

     

    My particular car – as the ASZ engine code, and should run fine with 505.01 specification or higher.

    Saturday, 12 March 2011

    ITIL Foundation Level Certificate – I’ve PASSED !!!! (82%)

    After a manic three day training for the ITIL Foundation Level course, I've passed with 82% pass mark, and here's my certificate !

     

    Wahoo

    Friday, 11 March 2011

    Energy Map of the Earthquake / Tsunami off the East Coast of Japan

    From : BBC News Feed of the Earthquake

    1949: An "energy map" provided by the US National Oceanic and Atmospheric Administration (NOAA) shows the intensity of the tsunami caused by the earthquake which struck Japan.

    Wednesday, 9 March 2011

    TopCashBack - basically free money, or a nice way to earn a discount

    If you need to shop online, why not get some discount to help towards to cost of your purchases.
    Marks and Spencer are one of the stores offering ~5% cashback on purchases!

    Register, and use TopCashBack when purchasing your goods, and you'll soon be saving a tidy amount.

    To start earning CashBack, you'll need to follow these very simple steps:
    1. Register an account with TopCashBack.
    2. Search TopCashBack for the website that has the goods that you want to buy.
    3. Click on the link in the results of your search on TopCashBack, which should land you on the "shopping" site.

      Depending on the relationship between TopCashBack and the shopping site, you will earn CashBack by completing a transaction, or just for the visit to the shopping site, or for performing a search on the shopping site. There's a few different ways that results in a valid CashBack generating transaction.
    Using TopCashBack doesn't cost you any money, and once set-up, you'll start to earn CashBack in no time !

    Thursday, 3 March 2011

    Applying for a Vehicle Tax Disc

    To check and purchase your vehicle tax disc online, visit the following link:

    http://www.taxdisc.direct.gov.uk/EvlPortalApp/


    You'll need either

    1. The reference number shown on the TAX DISC reminder document that's sent in the post

    OR

    1. The registration number of the vehicle
    2. And the V5C document reference number shown on the logbook


    Sunday, 27 February 2011

    Skoda Fabia – Boot Strut fitment guide

    (credit to : http://www.tailgatestruts.com/gas-strut-fitting-mounting)

    How to Fit & Remove Tailgate Struts

    Band Type Ball Sockets

    Removing and installing gas struts on your car is often a quick and simple job which does not require a mechanic.
    If your gas struts have a ball and socket fittings then the only tools required are flat blade screwdriver and someone to hold the boot for you.

    Look at the end of the gas strut for a rectangular plastic block with a metal band running around the back.
    Some struts use metal fittings but the band will be in a similar position.

    • Slide a flat head screwdriver down the groove along the back of the fitting and under the metal band.
    • Lever the band back and pull on the gas strut to remove it from the car. You do not need to remove the band to do this – just lever it back.
    • Your new gas struts will simply push fit back onto the ball studs.


    Replacing car tailgate struts is a two person job.
     
    Do not remove one strut and rely on the other to hold the tailgate.

     

    Pin Type Ball Sockets

    If your gas struts have a dome end fitting with a small metal pin -

    • Unclip the pin from around the base of the fitting and totally remove it from the fitting.
    • Once the pin is removed the gas strut can be pulled off, leaving the ball attached to the vehicle.
    • To fit your new struts remove the pin, push fit them onto the ball stud and replace the pin.


    Skoda Fabia – Boot Strut

    Model: Skoda Fabia Hatchback Gas Strut
    Body: Hatchback
    Year: 1999 - 2007
    Part#: 6Y0827550A 7969MW

     

     

    http://www.tailgatestruts.com/gsc2142-skoda-fabia-tailgate-strut

     

     


     

    Other suppliers: SGS Engineering £13.99

    Thursday, 17 February 2011

    SQL – Simple way to return messages at runtime instead of using PRINT

    Care of David Poole of SQLServerCentral: http://www.sqlservercentral.com/articles/Documentation/72473/

     

     

    RAISERROR ( 'DATA DICTIONARY: %i tables & %i fields added', 10, 1,

        @TableCount, @FieldCount ) WITH NOWAIT




    The "10" parameter is the SEVERITY of the error message raised.

    10 : this is more of a notice message, or minor alert

    16 : this is reserved for true error messages


    You can find more via:
    http://www.sqlservercentral.com/articles/SQL+Puzzles/quickhintsforusingtheraiserrorcommand/2114/

    http://msdn.microsoft.com/en-us/library/ms178592.aspx