Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 114 total

grant exec to all stored proc for sql 2005

// grant exec to all stored proc for sql 2005

CREATE PROCEDURE spGrantExectoAllStoredProcs @user sysname
AS 

/*----------------------------------------------------------------------------
-- Object Name: spGrantExectoAllStoredProcs
-- Author: Edgewood Solutions
-- Development Date: 03.19.2007
-- Called By: TBD
-- Description: Issue GRANT EXEC statement for all stored procedures 
-- based on the user name that is passed in to this stored procedure
-- Project: SQL Server Security
-- Database: User defined databases 
-- Business Process: SQL Server Security
-- 
----------------------------------------------------------------------------
-- Num | CRF ID | Date Modified | Developer | Description
----------------------------------------------------------------------------
-- 001 | N\A      | 03.15.2007    | Edgewood | Original code for the GRANT 
-- EXEC process
--
-- 
*/

SET NOCOUNT ON

-- 1 - Variable declarations
DECLARE @CMD1 varchar(8000)
DECLARE @MAXOID int
DECLARE @OwnerName varchar(128)
DECLARE @ObjectName varchar(128)

-- 2 - Create temporary table
CREATE TABLE #StoredProcedures
(OID int IDENTITY (1,1),
StoredProcOwner varchar(128) NOT NULL,
StoredProcName varchar(128) NOT NULL)

-- 3 - Populate temporary table
INSERT INTO #StoredProcedures (StoredProcOwner, StoredProcName)
SELECT ROUTINE_SCHEMA, ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_NAME NOT LIKE 'dt_%'
AND ROUTINE_TYPE = 'PROCEDURE'

-- 4 - Capture the @MAXOID value
SELECT @MAXOID = MAX(OID) FROM #StoredProcedures

-- 5 - WHILE loop
WHILE @MAXOID > 0
BEGIN 

-- 6 - Initialize the variables
SELECT @OwnerName = StoredProcOwner,
@ObjectName = StoredProcName
FROM #StoredProcedures
WHERE OID = @MAXOID

-- 7 - Build the string
SELECT @CMD1 = 'GRANT EXEC ON ' + '[' + @OwnerName + ']' + '.' + '[' + @ObjectName + ']' + ' TO ' + @user

-- 8 - Execute the string
-- SELECT @CMD1
EXEC(@CMD1)

-- 9 - Decrement @MAXOID
SET @MAXOID = @MAXOID - 1
END

-- 10 - Drop the temporary table
DROP TABLE #StoredProcedures

SET NOCOUNT OFF
GO

PHP : Filas al azar / Random Rows

Filas al azar / Random Rows

function dame_unas_filas_al_azar($tabla,$numero_de_filas)
{
$sql="SELECT * FROM ".$tabla." ORDER BY RAND(NOW()) LIMIT ".$numero_de_filas;
$resultado = mysql_query($sql);
	if($resultado)
	{
	return mysql_fetch_array($resultado);
	}
	else
	{
	return false;
	}
}

Select DataBase Schema

// Select database schema.
//This could be used to recreate or test for existence of columns/tables
//or could also be used to create a database template system to enable the writing //of database schema into txt template file to be recreated again by reading the //txt file via an application
//
//You can also use SELECT * instead of defining each schema property (column)

SELECT TABLE_CATALOG
, TABLE_SCHEMA
, TABLE_NAME
, ORDINAL_POSITION
, COLUMN_DEFAULT
, IS_NULLABLE
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, COLLATION_NAME 
FROM 
INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = (N'Persons')

SQL -> Check Column exists in table, if not, add

// Check to see if column exists and then create if not

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME =TEST’ AND COLUMN_NAME =TEST_DATE’)
BEGIN
   ALTER TABLE TEST ADD TEST_DATE DATETIME
END

DELETE - SQL

// description of your code here

DELETE ... 
    [ FROM ... ] 
    [ ... JOIN ... ] 
    [ WHERE ... ] 

// FULL Syntax follows:
DELETE [ FROM ] 
    {
       [ database. ] [ owner. ] table_name 
         [
           WITH (  INDEX ( Index_1,   [ index_2,  ...,  n ] ) 
                      | FASTFIRSTROW 
                      | HOLDLOCK 
                      | PAGLOCK 
                      | READCOMMITTED 
                      | REPEATABLEREAD 
                      | ROWLOCK 
                      | SERIALIZABLE 
                      | TABLOCK 
                      | TABLOCKX 
                      [   ...   n  |  ...,  n ] 
                     )
       ]
     |
       OPENQUERY( server, 'query' ) 
     |
       OPENROWSET( 'provider_name', 
                                 { 'datasource';'user_id';'password',  |  'provider_string', }
                                 { [ catalog. ] [ schema. ] object  |  'query' }
                               ) 
     |
       view_name 
    }

    [
      FROM 
      {
          derived_table 
            [ [ AS ] table_alias ]
            [ ( column_alias_1,   [ column_alias_2,   ...,  n ]  )  ]
        |
          CONTAINSTABLE ( table, column  |  *, 'search_conditions' ) 
            [ [ AS ] table_alias ]
        |
          FREETEXTTABLE ( table, column  |  *, 'free_text_string' ) 
            [ [ AS ] table_alias ]
        |
          table_name [ [ AS ] table_alias ]
            [
               WITH (  INDEX ( Index_1,   [ index_2,   ...,  n ]  ) 
                          | FASTFIRSTROW 
                          | HOLDLOCK 
                          | NOLOCK 
                          | PAGLOCK 
                          | READCOMMITTED 
                          | READPAST 
                          | READUNCOMMITTED 
                          | REPEATABLEREAD 
                          | ROWLOCK 
                          | SERIALIZABLE 
                          | TABLOCK 
                          | TABLOCKX 
                          | UPDLOCK 
                          [ ...   n  |  ...,  n ] 
                         )
            ]
        |
          view_name [ [ AS ] table_alias ]
      }





      [
          INNER JOIN  |  LEFT [ OUTER ] JOIN  |  RIGHT [ OUTER ] JOIN 
            {
               derived_table [ ON search_conditions ]
             |
               OPENQUERY( server, 'query' ) [ ON search_conditions ]
             |
               OPENROWSET
                               ( 'provider_name', 
                                 { 'datasource';'user_id';'password',  |  'provider_string', }
                                 { [ catalog. ] [ schema. ] object  |  'query' }
                               ) [ ON search_conditions ]
             | 
               table_name [ ON search_conditions ]
             | 
               view_name [ ON search_conditions ]
            }
            [   ...,  n ]
          |
          CROSS JOIN  |  FULL [ OUTER ] JOIN 
            {
               derived_table 
             | 
               OPENQUERY( server, 'query' ) 
             |
               OPENROWSET
                               ( 'provider_name', 
                                 { 'datasource';'user_id';'password',  |  'provider_string', }
                                 { [ catalog. ] [ schema. ] object  |  'query' }
                               ) 
             | 
               table_name 
             | 
               view_name 
            }
            [   ...,  n ]
       ]
   ] 

   [
      {
         WHERE search_conditions 
       |
         WHERE CURRENT OF [ GLOBAL ] cursor_name 
       |
         WHERE CURRENT OF cursor_variable_name 
      }
         [
           OPTION (  FAST number_rows 
                          | FORCE ORDER 
                          | HASH GROUP 
                          | ORDER GROUP 
                          | HASH JOIN 
                          | LOOP JOIN 
                          | MERGE JOIN 
                          | KEEP PLAN 
                          | MAXDOP 
                          | ROBUST PLAN 
                          | CONCAT UNION 
                          | HASH UNION 
                          | MERGE UNION 
                          [   ...,  n ]
                        )
         ]
   ]

//Full explanation follows:

KEYWORDS Keywords are denoted with upper case letters. Obey the spelling.

variables All user-supplied variables are denoted with lower case letters.

..., n Signifies that there can be more than one value in a comma delimited list. Note that the dots and n are not part of the code and must not appear in the SQL query.

... n Signifies that there can be more than one value in a blank space delimited list. Note that the dots and n are not part of the code and must not appear in the SQL query.

{ } Signifies that all, or some portion, of the code elements between the braces are required elements and must appear in the SQL query. Note that these braces are not part of the code and must not appear in the SQL query.

[ ] Signifies that the code elements between the square brackets can optionally appear in the SQL query, but are not required. Note that these brackets are not part of the code and must not appear in the SQL query.

| The or symbol signifies that you may use only one of the code elements or values from the possible choices. Note that the or symbol is not part of the code and must not appear in the SQL query.

Simulate a (mysql)LIMIT on "MS SQLserver"

return lines from 7995 to 8000 (5 lines)

select * from (
select top 5 * from 
(select top 8000 * from TABLE order by 1 asc) as tbl1 order by 1 desc 
) as tbl2 order by 1 asc

SQL SERVER: Delete Duplicate Rows with Primary Id

Deletes duplicates (leaving one instance) where the table has a primary key. Good for tables with Id, DupColumn, DupColumn...

(This is MS-SQL specific)

DELETE
FROM 	TableName
WHERE 	Id NOT IN
	(SELECT 	MAX(Id)
        FROM   		TableName
        GROUP BY 	DuplicateColumName1, DuplicateColumName2)

unix wizards of the realm:

// SVN ignore based on .cvsignore file:

svn propset svn:ignore -F .cvsignore .


// grep:
with line number: -nwith file name: -H


// os x housekeeping:


// install perl module:
sudo perl -MCPAN -e 'install Bundle::LWP'


// meta refresh (i have never typed this line start to finish in my life. i have probably copy-pasted it 7,000 times
<meta http-equiv=Refresh content="0; URL=http://blog.jm3.net/" />


// get files off codeswami:
ssh -l cs 208.101.26.91


// SQL tricks:
http://jm3.net/cgi-bin/safe/wiki.pl?MySqlLibrary

Storm ORM by Canonical in WSGI enabled applications

#!/usr/bin/env python
# vim:ts=4:sw=4:et
# (c) 2007 Vsevolod Balashov <vsevolod@balashov.name> under terms of LGPL 2.1
# use Storm ORM <https://storm.canonical.com> in WSGI enabled applications

"""WSGI middleware for Storm.

This is the database access inteface for WSGI enabled (PEP 333) web applications.

Pylons framework example:

in wsgiapp.py

from storm.database import create_database
from middlestorm import MiddleStorm
...

# CUSTOM MIDDLEWARE HERE
app = MiddleStorm(app, create_database(config['app_conf']['sqlalchemy.default.uri']))

in controller:

class DemoController(BaseController):
    def index(self):
        store = request.environ['storm.store']
        ...
"""

from storm.database import Database
from storm.store import Store
from threading import local

__all__ = ["MiddleStorm"]
__author__ = "Vsevolod Balashov <http://vsevolod.balashov.name>"
__version__ = "0.1"

class SingleConn(Database):
    """Database proxy class.
    Share single database connection between all Store object instances in threads.
    If you have readonly database or not use transactions why not?
    """
    def __init__(self, database):
        self._database = database
        self._connection = database.connect()
    def connect(self):
        return self._connection

class MiddleStorm(object):
    """WSGI middleware.
    Add Store object instance in environ['storm.store']. Each thread contains own instance.
    """

    def __init__(self, app, database, single = False):
        """Create WSGI middleware.
        @param app: up level application or middleware.
        @param database: instance of Database returned create_database.
        @param: single: use single database connection in all threads. 
        """
        assert isinstance(database, Database), \
            'database must be subclass of storm.database.Database'
        if single:
            self._database = SingleConn(database)
        else:
            self._database = database
        self._app = app
        self._local = local()

    def __call__(self, environ, start_response):
        try:
            environ['storm.store']  = self._local.store
        except AttributeError:
            environ['storm.store']  = \
                self._local.__dict__.setdefault('store', Store(self._database))
        return self._app(environ, start_response)

PHP : Conectar con Access / Connect with Access

Conectar con Access / Connect with Access.
Código fuente / Source code :

$pathDB = str_replace("/", "\\", $_SERVER["DOCUMENT_ROOT"]) . "\\directory1\\directory2\\bdd.mdb";

if(!file_exists($pathDB))
{
echo "!!! Base de datos no encontrada ".$pathDB;
exit;
}

$conexion = odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$pathDB, "ADODB.Connection", "", "SQL_CUR_USE_ODBC");
$sql="select * from tabla where 1";
$resultado=odbc_exec($conexion,$sql);
if($resultado)
{
	while($fila=odbc_fetch_array($resultado))
	{
	echo $fila['campo1']."<br />";
	echo $fila['campo2']."<br />";
	}
odbc_close_all();
}
« Newer Snippets
Older Snippets »
Showing 11-20 of 114 total