working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,251 snippets matching: stored

    public by mporru @ Amazon_AWS_PHP_API  320871  0  5  0

    Amazon AWS - PHP: Generate signed expiring download URL

    This snippet demonstrates how to generate a download URL for a file stored in your S3 Bucket. This will work for all files, even ACL private files. Download URL will be active for the specified time. In order to use this service you must enable Amazon Simple Storage Service (Amazon S3) in your account.
    <?php
    require_once('sdk.class.php');
    $s3 = new AmazonS3();
    
    $fileName = 'test1.txt';
    $bucketName = 'myBucketName';
    
    $url = $s3->get_object_url($bucketName, $fileName, '1 hour');
    
    echo("Download url: <a href=\"$url\">$url</a>\n");
    ?>

    public by cghersi  105504  654  11  10

    Java: read from USB using RXTX library

    This is a well-tested class to read from USB device using RXTX library. First of all place rxtxSerial.so (or rxtxSerial.dll) in the classpath. The received bytes are stored in a queue called "receivedBytes". This queue is filled by the serialEvent() callback called by RXTX framework. Users of this class should retrieve the ready data from "receiv
    import gnu.io.*;
    import java.io.*;
    
    import java.util.Enumeration;
    import java.io.IOException;
    
    /**
     * This class provides the utilities to read the data exchanged via USB port.
     */
    public class USBComm implements SerialPortEventListener {
    
    	/**
    	 * Stream for the storage of incoming data
    	 */
    	private InputStream inputStream;
    	/**
    	 * Stream for the dispatching of data
    	 */
    	private OutputStream outputStream;
    	/**
    	 * Timeout of the USB port
    	 */
    	private final int PORT_TIMEOUT = 2000;
    	/**
    	 * Representation of the serial port used for the communication
    	 */
    	private SerialPort serialPort;
    	/**
    	 * Buffer that stores the received bytes from the media
    	 */
    	protected LinkedBlockingQueue<Byte> receivedBytes;
    
    	/**
    	 * Builds a new manager for the communication via USB port.
    	 * @exception IOException if an error occurred during the opening of the USB port
    	 */
    	public USBComm() throws IOException {
    	  receivedBytes = new LinkedBlockingQueue<Byte>(100000);
    		String port = "COM1"; //place the right COM port here, OS dependent
    	
    		//Check that the USB port exists and is recognized:
    		Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
    		boolean portFound = false;
    		CommPortIdentifier portId = null;
    		while (portList.hasMoreElements()) {
    			portId = (CommPortIdentifier) portList.nextElement();
    		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    		    	System.out.println.info(portId.getName());
    				if (portId.getName().equals(port)) {
    					System.out.println("Found port: " + port);
    				    portFound = true;
    				    break;
    				} 
    		    } 
    		} 
    	
    		if (!portFound) 
    		    throw new IOException("port " + port + " not found.");
    	
    		try {
    			System.out.println("USB port opening...");
    		    serialPort = (SerialPort) portId.open("USBCommunicator", PORT_TIMEOUT);
    		    System.out.println("USB port opened");
    		    inputStream = serialPort.getInputStream();
    		    outputStream = serialPort.getOutputStream();
    		    serialPort.addEventListener(this);
    			    	serialPort.notifyOnDataAvailable(true);
    			//#==================================================================#
    			// WARNING! - DO NOT SET THE FOLLOWING PROPERTY WITH RXTX LIBRARY, IT
    			// 			  CAUSES A PROGRAM LOCK:
    			// 	serialPort.notifyOnOutputEmpty(true);
    			//#==================================================================#
    			    	
    		    //wait for a while to leave the time to javax.comm to
    		    //correctly configure the port:
    		    Thread.sleep(1000);
    		    
    			int baudRate = 115200; //set propertly
    	    	serialPort.setSerialPortParams(baudRate, 
    	    		SerialPort.DATABITS_8, 
    	    		SerialPort.STOPBITS_1, 
    				SerialPort.PARITY_NONE);
    		    
    	    	serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    	    		
    		    System.out.println("setted SerialPortParams");
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    			throw new IOException(e.getMessage());
    		}
    	}
    
    	
    	public void closeUSB(){
    		//close the streams for serial port:
    		try {
    			inputStream.close();
    			outputStream.close();
    		} catch (IOException e) {
    			System.err.println("Cannot close streams:" + e.getMessage(), e);
    		}
    	}
    
    	/**
    	 * Listener for USB events
    	 * 
    	 * @param event new event occurred on the USB port
    	 */
    	public void serialEvent(SerialPortEvent event){
    		switch (event.getEventType()) {
    	
    			case SerialPortEvent.BI:
    			case SerialPortEvent.OE:
    			case SerialPortEvent.FE:
    			case SerialPortEvent.PE:
    			case SerialPortEvent.CD:
    			case SerialPortEvent.CTS:
    			case SerialPortEvent.DSR:
    			case SerialPortEvent.RI:
    			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    				//nothing to do...
    			    break;
    	
    			case SerialPortEvent.DATA_AVAILABLE:
    				byte received = -1;
    				do {
    					try {
    						received = (byte)inputStream.read();
    					} catch (IOException e) {
    						System.err.println("Error reading USB:" + e.getMessage());
    					}
    				
    					synchronized (receivedBytes) {
    						try {
    							receivedBytes.add(received);
    						} catch (IllegalStateException ew) {
    							System.err.println(ew.getMessage());
    							receivedBytes.poll();
    							receivedBytes.add(received);
    						}
    					}
    				} while(received != -1);
    
    			    break;
    		}
    	}
    
    	protected void write(byte[] buffer){
    	    try {
    	    	outputStream.write(buffer);
    	    	outputStream.flush();
    	    } catch (IOException e) {
    	    	System.err.println("Cannot write:" + e.getMessage());
    	    }
    	}
    }            

    public by christopher  169670  0  4  0

    Copied from my local repo (Not pushed fully to a branch on github itself.) For preview purpose for a friend. Just a standard BlockStateUtil that is going to be used to compare block states for restoration.. This is very basic. To remove the bk...

    Copied from my local repo (Not pushed fully to a branch on github itself.) For preview purpose for a friend. Just a standard BlockStateUtil that is going to be used to compare block states for restoration.. This is very basic. To remove the bkcommonlib dependency remove the blockStatesMatch function.. The Pair is nothing but a class wit
    package com.noxpvp.core.utils;
    
    import java.util.logging.Level;
    
    import org.bukkit.block.Beacon;
    import org.bukkit.block.BlockState;
    import org.bukkit.block.BrewingStand;
    import org.bukkit.block.Chest;
    import org.bukkit.block.CommandBlock;
    import org.bukkit.block.CreatureSpawner;
    import org.bukkit.block.Dispenser;
    import org.bukkit.block.Dropper;
    import org.bukkit.block.Furnace;
    import org.bukkit.block.Hopper;
    import org.bukkit.block.Jukebox;
    import org.bukkit.block.NoteBlock;
    import org.bukkit.block.Sign;
    import org.bukkit.block.Skull;
    import org.bukkit.inventory.BeaconInventory;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.InventoryHolder;
    
    import com.bergerkiller.bukkit.common.filtering.Filter;
    import com.noxpvp.core.NoxCore;
    import com.noxpvp.core.data.Pair;
    
    public class BlockStateUtils {
    	
    	public static boolean blockStatesMatch(BlockState state1, BlockState state2, Filter<Pair<BlockState>>... filters)
    	{
    		Pair<BlockState> states = new Pair<BlockState>(state1, state2);
    		
    		for (Filter<Pair<BlockState>> filter : filters)
    			if (!filter.isFiltered(states))
    				return false;
    		return true;
    	}
    	
    	public static boolean blockStatesPerfectMatch(BlockState state1, BlockState state2)
    	{
    		if (!state1.getBlock().equals(state2.getBlock()))
    			return false;
    		
    		if (!state1.getType().equals(state2.getType()))
    			return false;
    		
    		if (state1 instanceof Chest) { // No need to check other state for instance since they both match types!
    			if (!isChestMatch((Chest)state1, (Chest)state2))
    				return false;
    		} else if (state1 instanceof Beacon) {
    			if (!isBeaconMatch((Beacon)state1, (Beacon)state2))
    				return false;
    		} else if (state1 instanceof BrewingStand) {
    			if (!isBrewingStandMatch((BrewingStand)state1, (BrewingStand)state2))
    				return false;
    //		} else if (state1 instanceof Dispenser) {
    //			if (!isInventoryHolderMatch((InventoryHolder)state1, (InventoryHolder) state2))
    //				return false;
    //		} else if (state1 instanceof Dropper) {
    //			if (!isDropperMatch((Dropper)state1, (Dropper) state2))
    //				return false;
    //		} else if (state1 instanceof Hopper) {
    //			if (!isHopperMatch((Hopper)state1, (Hopper)state2))
    //				return false;
    		} else if (state1 instanceof Furnace) {
    			if (!isFurnaceMatch((Furnace)state1, (Furnace)state2))
    				return false;
    		} else if (state1 instanceof InventoryHolder) { ///Must come after Furnace (As its also an inventory holder!)
    			if (!isInventoryHolderMatch((InventoryHolder)state1, (InventoryHolder)state2))
    				return false;
    		} else if (state1 instanceof CommandBlock) {
    			if (!isCommandBlockMatch((CommandBlock)state1, (CommandBlock)state2))
    				return false;
    		} else if (state1 instanceof CreatureSpawner) {
    			if (!isSpawnerMatch((CreatureSpawner)state1, (CreatureSpawner)state2))
    				return false;
    		} else if (state1 instanceof Jukebox) {
    			if (!isJukeboxMatch((Jukebox)state1, (Jukebox)state2))
    				return false;
    		} else if (state1 instanceof NoteBlock) {
    			if (!isNoteBlockMatch((NoteBlock)state1, (NoteBlock)state2))
    				return false;
    		} else if (state1 instanceof Sign) {
    			if (!isSignMatch((Sign)state1, (Sign)state2))
    				return false;
    		} else if (state1 instanceof Skull) {
    			if (!isSkullMatch((Skull)state1, (Skull)state2))
    				return false;
    		}
    		
    		return true;
    	}
    	
    	private static boolean isSkullMatch(Skull state1, Skull state2) {
    		if (!state1.getSkullType().equals(state2.getSkullType()))
    			return false;
    		
    		if (!state1.getRotation().equals(state2.getRotation()))
    			return false;
    		
    		if (!state1.getOwner().equals(state2.getOwner()))
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isSignMatch(Sign state1, Sign state2) {
    		for (int i = 0; i < 3; i++)
    			if (!state1.getLine(i).equals(state2.getLine(i)))
    				return false;
    		
    		return true;
    	}
    
    	private static boolean isNoteBlockMatch(NoteBlock state1, NoteBlock state2) {
    		if (!state1.getNote().equals(state2.getNote()))
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isJukeboxMatch(Jukebox state1, Jukebox state2) {
    		if (!state1.getPlaying().equals(state2.getPlaying()))
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isHopperMatch(Hopper state1, Hopper state2) {
    		return isInventoryHolderMatch(state1, state2);
    	}
    	
    	private static boolean isDropperMatch(Dropper state1, Dropper state2) {
    		return isInventoryHolderMatch(state1, state2);
    	}
    
    	private static boolean isFurnaceMatch(Furnace state1, Furnace state2) {
    		if (state1.getBurnTime() != state2.getBurnTime())
    			return false;
    		if (state1.getCookTime() != state2.getCookTime())
    			return false;
    		
    		return isInventoryHolderMatch(state1, state2);
    	}
    
    	private static boolean isInventoryHolderMatch(InventoryHolder state1, InventoryHolder state2) {
    		Inventory inv1 = state1.getInventory(), inv2 = state2.getInventory();
    		
    		if (inv1.getSize() != inv2.getSize())
    			return false;
    		
    		if (!inv1.getName().equals(inv2.getName()))
    			return false;
    		
    		if (!inv1.getTitle().equals(inv2.getTitle()))
    			return false;
    		
    		for (int i = 0; i < inv1.getSize(); i++)
    			if (!inv1.getItem(i).equals(inv2.getItem(i)))
    				return false;
    		
    		return true;
    	}
    
    	private static boolean isSpawnerMatch(CreatureSpawner state1, CreatureSpawner state2) {
    		if (!state1.getSpawnedType().equals(state2.getSpawnedType()))
    			return false;
    		
    		if (!state1.getCreatureTypeName().equals(state2.getCreatureTypeName()))
    			return false;
    		
    		if (state1.getDelay() != state2.getDelay())
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isCommandBlockMatch(CommandBlock state1, CommandBlock state2) {
    		if (!state1.getName().equals(state2.getName()))
    			return false;
    		
    		if (!state1.getCommand().equals(state2.getCommand()))
    			return false;
    		
    		return true;
    	}
    
    	private static boolean isBrewingStandMatch(BrewingStand stand1, BrewingStand stand2)
    	{
    		//TODO: Determine if we wanna match items brewing and such
    		return true;
    	}
    	
    	private static boolean isBeaconMatch(Beacon beacon1, Beacon beacon2)
    	{
    		Inventory rInv1 = beacon1.getInventory(), rInv2 = beacon2.getInventory();
    		
    		try {
    			BeaconInventory inv1 = (BeaconInventory)rInv1, inv2 = (BeaconInventory)rInv2;
    			
    			if (!inv1.getItem().equals(inv2.getItem()))
    				return false;
    				
    		} catch (ClassCastException e) {
    			NoxCore.getInstance().log(Level.SEVERE, "Bukkit is not using their own api for beacons! SUBMIT BUT REPORT TO THEM! \n Defaulting to Plain inventory Code!");
    			return isInventoryHolderMatch(beacon1, beacon2);
    		}
    		return true;
    	}
    	
    	private static boolean isChestMatch(Chest state1, Chest state2)
    	{
    		return isInventoryHolderMatch(state1, state2);
    	}
    }
    
    
    

    public by cghersi  4144  1  7  0

    Testing script for Stored Procedures

    This script helps developers test the performance of a stored procedure or block of code. Although it was written specifically to assist me in comparing stored procedures, it can easily be modified for other testing purposes. The script expects two tables, 'Seq1' and 'Seq2' to exist, and be of the structure as listed in the header comment of the
    /*************************************************************************************************
    ** File: "20090217 - testing script.sql"
    ** Desc: This is a more generalized script to run performance testing on the sequence 
    ** comparison code. It can be modified to test any other spds. This script requires
    ** the existence of two tables, Seq1 and Seq2, which should have the following structure:
    ** 
    ** CREATE TABLE Seq1 (
    **   CodeLineTxt varchar(max), /* stores the original line of code */
    **   CodeLineNum int not null identity(1,1), /* stores the line number */
    **   MatchLineNum int /* stores the matching line of code from spd #2 */
    ** )
    ** 
    ** Return values: report & results
    ** 
    ** Called by: 
    ** 
    ** Parameters:
    ** Input
    ** ----------
    ** none
    **
    ** Output
    ** -----------
    ** none
    **
    ** Auth: Jesse McLain
    ** Email: jesse@jessemclain.com
    ** Web: www.jessemclain.com
    ** Blog: http://jessesql.blogspot.com/2009/02/comparing-spds-part-3-performance.html
    **
    ** Date: 02/16/2008
    **
    ***************************************************************************************************
    ** Change History
    ***************************************************************************************************
    ** Date:    Author:         Description:
    ** -------- --------        -------------------------------------------
    ** 20080216 Jesse McLain    Created script
    **************************************************************************************************/
    
    SET NOCOUNT ON
    
    DECLARE @RunsPerInputSize int         ; SET @RunsPerInputSize = 1      /* #runs of @InputSize to execute */
    DECLARE @InputSizeIncrement int       ; SET @InputSizeIncrement = 50   /* @InputSize to increment btwn outer runs */
    DECLARE @TotalNumberIncrements int    ; SET @TotalNumberIncrements = 1 /* #increments to execute */
    
    DECLARE @StartTime datetime           ; SET @StartTime = GETDATE()
    DECLARE @StopTime datetime            ; SET @StopTime = GETDATE()
    DECLARE @Seq1 varchar(max)            ; SET @Seq1 = 'Test Sequence "'
    DECLARE @Seq2 varchar(max)            ; SET @Seq2 = 'Test Sequence "'
    DECLARE @TestValue varchar(2)         ; SET @TestValue = ''             /* holder to load values into seq tables */
    DECLARE @InputSize int                ; SET @InputSize = 0              /* input size for the current run */
    DECLARE @InputValueIdx int            ; SET @InputValueIdx = 1          /* counter */
    DECLARE @RunIdx int                   ; SET @RunIdx = 1                 /* counter */
    DECLARE @IncrIdx int                  ; SET @IncrIdx = 1                /* counter */
    DECLARE @Seq1Size int
    DECLARE @Seq2Size int
    DECLARE @Seq1Sizea int
    DECLARE @Seq2Sizea int
    DECLARE @PcntMatch decimal(9, 2)
    
    CREATE TABLE #PerformanceResults (
      InputSize int,
      RunStart datetime,
      RunDone datetime,
      PcntMatch decimal(9, 2)
    )
    
    /* the straight-forward approach to testing would be to start at the smallest
    input size, run through as many runs as we need for that, move on to the next
    input size, test that, until we test the max input size. We don't do that here.
    The problem with that approach is that if there's an external process running
    during the testing of an input size, the results for that size might be false.
    The approach here is to test the min size once, then the next largest size, 
    until the max size is tested, then start all over and repeat until we've tested
    each inputsize as many as "@RunsPerInputSize" times. */
    
    SET @RunIdx = 1
    /* outer loop to increment the number of runs per input size */
    WHILE @RunIdx <= @RunsPerInputSize
    BEGIN
      SET @IncrIdx = 1
      /* inner loop to increment each input size */
      WHILE @IncrIdx <= @TotalNumberIncrements
      BEGIN
        PRINT 'Testing size ' + LTRIM(STR(@IncrIdx)) + '/' + LTRIM(STR(@TotalNumberIncrements))
         + ', for run ' + LTRIM(STR(@RunIdx)) + '/' + LTRIM(STR(@RunsPerInputSize))
     
        SET @InputSize = @IncrIdx * @InputSizeIncrement
     
     
        /* insert rows into test table 1 */
        TRUNCATE TABLE Seq1
        SET @InputValueIdx = 1
        WHILE @InputValueIdx <= @InputSize
        BEGIN
          SET @TestValue = CHAR(FLOOR(RAND() * 10) + 65) + CHAR(FLOOR(RAND() * 10) + 65)
          INSERT INTO Seq1 (CodeLineTxt) VALUES (@TestValue)
          SET @Seq1 = @Seq1 + @TestValue
          SET @InputValueIdx = @InputValueIdx + 1
        END
        UPDATE Seq1 SET MatchLineNum = 0
        SET @Seq1 = @Seq1 + '"'
    
    
        /* insert rows into test table 2 */
        TRUNCATE TABLE Seq2
        SET @InputValueIdx = 1
        WHILE @InputValueIdx <= @InputSize
        BEGIN
          SET @TestValue = CHAR(FLOOR(RAND() * 10) + 65) + CHAR(FLOOR(RAND() * 10) + 65)
          INSERT INTO Seq2 (CodeLineTxt) VALUES (@TestValue)
          SET @Seq2 = @Seq2 + @TestValue
          SET @InputValueIdx = @InputValueIdx + 1
        END
        UPDATE Seq2 SET MatchLineNum = 0
        SET @Seq2 = @Seq2 + '"'
    
    
        /* wrap the executing code around timers to test */
        SET @StartTime = GETDATE()
      
        EXEC spd_SequenceCompare
    
        SET @StopTime = GETDATE()
    
    
        /* record results */
        SELECT @Seq1Size = COUNT(*) FROM Seq1
        SELECT @Seq2Size = COUNT(*) FROM Seq2
      
        SELECT @Seq1Sizea = COUNT(*) FROM Seq1 T1 WHERE MatchLineNum <> 0
        SELECT @Seq2Sizea = COUNT(*) FROM Seq2 T1 WHERE MatchLineNum <> 0
      
        SET @PcntMatch = 100.0 * (@Seq1Sizea / (1.0 * @Seq1Size) + @Seq2Sizea / (1.0 * @Seq2Size)) / 2
    
        INSERT INTO #PerformanceResults (InputSize, RunStart, RunDone, PcntMatch)
        VALUES (@InputSize, @StartTime, @StopTime, @PcntMatch)
     
        SET @IncrIdx = @IncrIdx + 1
      END
    
      SET @RunIdx = @RunIdx + 1
    END
    
    SELECT 
      InputSize, 
      NumberOfRuns = COUNT(*),
      AverageRunTime = AVG(CONVERT(decimal(9, 2), CONVERT(varchar(max), DATEDIFF(ss, RunStart, RunDone))
       + '.' + CONVERT(varchar(max), DATEDIFF(ms, RunStart, RunDone)))),
      AveragePercentMatch = AVG(PcntMatch)
    FROM #PerformanceResults
    GROUP BY InputSize
    
    
    DROP TABLE #PerformanceResults
    
    SET NOCOUNT OFF

    public by cghersi  2868  1  7  0

    Call Stored Procedure with OUT or INOUT parameters in MySQL

    This is how to call a stored procedure "MySP" with a parameter defined as INOUT directyl from SQL environment
    DELIMITER $$
    CREATE PROCEDURE MySP(
    	IN _Ip VARCHAR(20),
    	INOUT _Id INT
    )
    BEGIN
    	SELECT  Id INTO _Id 
    	FROM    `MyTable`
    	WHERE   Ip = _Ip ;
    END $$
    DELIMITER ;
    
    SET @a = 1;
    CALL MySP('192.168.2.3', @a);

    public by lbottaro  2923  0  7  1

    Stored Procedure to solve error about Agent XPs in SQL Server on Maintenance Plan

    This is how to solve the error in Microsoft SQL Server Management Studio, when trying to create a Maintenance Plan. The error you get is the following. Error Message: ‘Agent XPs’ component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘Agent XPs’ by using sp_configure. For mo
    sp_configure 'show advanced options', 1;
    GO
    RECONFIGURE;
    GO
    sp_configure 'Agent XPs', 1;
    GO
    RECONFIGURE
    GO            

    public by cghersi  3097  1  6  0

    Safe creation of Stored Procedure for MS SQL Server 2012

    The following example of Stored Procedure can be use as a template for the creation of every procedure that needs a transaction
    CREATE PROCEDURE [dbo].[TblName_ProcName]
    	@Param1 nvarchar(50)
    AS
    BEGIN
    	SET NOCOUNT ON;
    	SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
    	SET XACT_ABORT ON;
    
    	DECLARE @error int = 0;
    
    	BEGIN TRAN
    
    		-- do stuff; for each SQL instruction add the following statement to 
    		-- check the occurrence of an error: 
    		SET @error = @error + @@ERROR
    	
    	IF @error = 0
    		BEGIN
    			COMMIT;
    			RETURN 0;
    		END
    	ROLLBACK
    	RETURN -1;
    	
    END
    GO

    public by cghersi  2401  1  6  2

    C#: Read the output parameter of a stored procedure

    fetch the output parameter of the given SP and try to read it
    static public string ReadOutputParam(this SqlCommand sqlCmd, string outputParamName, string defaultValue = "")
    {
      object outputValue = defaultValue;
      if (!string.IsNullOrEmpty(outputParamName))
        outputValue = sqlCmd.Parameters[outputParamName].Value;
    
      if ((outputValue == null) || (outputValue.Equals(DBNull.Value)))
        return defaultValue;
      else
        return outputValue.ToString();
    }
    

    public by cghersi  2552  0  7  0

    How to create a new SqlCommand to invoke a Stored Procedure

    This method creates a new SqlCommand for a stored procedure invocation. It sets all the relevant information for a stored procedure that can be then executed in ADO.NET environment
    static public SqlCommand CreateStoredProc(SqlConnection connection, string name)
    {
         SqlCommand newSPCmd = new SqlCommand();
         newSPCmd.CommandType = CommandType.StoredProcedure;
         newSPCmd.Connection = connection;
         newSPCmd.CommandText = name;
         newSPCmd.CommandTimeout = WebConfig.Current.DBConnectionTimeout;   //default timeout for snip2code
         return newSPCmd;
    }

    public by cghersi  2517  0  5  0

    Stored Procedure with Transactions

    This is an effective way to write a stored procedure which needs to use transactions
    CREATE PROCEDURE [dbo].[Snippets_AddPropToSnippets] 
    	@PropName nvarchar(50),
    AS
    BEGIN
    	SET NOCOUNT ON;
    	SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
    	SET XACT_ABORT ON;
    
    	DECLARE @error int = 0;
    
    	BEGIN TRAN
    		-- do a query
    		SELECT	ID
    		FROM	Properties
    		WHERE	Name = @PropName
    		
    		-- save the eventual error condition (@@ERROR <> 0)
    		SET @error = @error + @@ERROR
    
    	--at the end of the transaction, check on cumulative error:
    	IF @error = 0
    		BEGIN
    			COMMIT;
    			RETURN 0;
    		END
    	ROLLBACK
    	RETURN -1;
    
    END
    • Public Snippets
    • Channels Snippets