Find Column in SQL table With Info Schema

by ebarcza 2/26/2013 12:56:00 PM
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%Export%'

Tags:

SQL SERVER

SQl Server Default Instance

by ebarcza 8/20/2012 6:00:00 AM

The default instance name for SQL Server is MSSQLSERVER

Tags:

SQL SERVER

Determine Size of a Table in SQL Server

by ebarcza 7/31/2012 9:46:00 AM

sp_spaceused ‘Tablename’

 

 

   1:  CREATE PROCEDURE GetAllTableSizes
   2:  AS
   3:  /*
   4:      Obtains spaced used data for ALL user tables in the database
   5:  */
   6:  DECLARE @TableName VARCHAR(100)    --For storing values in the cursor
   7:   
   8:  --Cursor to get the name of all user tables from the sysobjects listing
   9:  DECLARE tableCursor CURSOR
  10:  FOR 
  11:  select [name]
  12:  from dbo.sysobjects 
  13:  where  OBJECTPROPERTY(id, N'IsUserTable') = 1
  14:  FOR READ ONLY
  15:   
  16:  --A procedure level temp table to store the results
  17:  CREATE TABLE #TempTable
  18:  (
  19:      tableName varchar(100),
  20:      numberofRows varchar(100),
  21:      reservedSize varchar(50),
  22:      dataSize varchar(50),
  23:      indexSize varchar(50),
  24:      unusedSize varchar(50)
  25:  )
  26:   
  27:  --Open the cursor
  28:  OPEN tableCursor
  29:   
  30:  --Get the first table name from the cursor
  31:  FETCH NEXT FROM tableCursor INTO @TableName
  32:   
  33:  --Loop until the cursor was not able to fetch
  34:  WHILE (@@Fetch_Status >= 0)
  35:  BEGIN
  36:      --Dump the results of the sp_spaceused query to the temp table
  37:      INSERT  #TempTable
  38:          EXEC sp_spaceused @TableName
  39:   
  40:      --Get the next table name
  41:      FETCH NEXT FROM tableCursor INTO @TableName
  42:  END
  43:   
  44:  --Get rid of the cursor
  45:  CLOSE tableCursor
  46:  DEALLOCATE tableCursor
  47:   
  48:  --Select all records so we can use the reults
  49:  SELECT * 
  50:  FROM #TempTable
  51:   
  52:  --Final cleanup!
  53:  DROP TABLE #TempTable
  54:   
  55:  GO 

Tags:

SQL SERVER

SQl 2008 Shrinking the transaction Log

by ebarcza 7/31/2012 9:38:00 AM

When issuesing these TSQL commands, make sure you're an admin and the target database is selected/active

 

  1. Open a query window
  2. make sure your target database is active by issueing a 'use databasename' statement, or selecting the appropriate database in the dropdown
  3. Change the Recovery Model to Simple; Alter database databaseName SET Recovery Simple
  4. Shrink the file using DBCC ShrinkFile; DBCC Shrinkfile('Logical name of Log', 1)
  5. Then switch it back to FULL database recovery mode if desired


Tags:

SQL SERVER

The INSTANCESHAREDDIR command line value was not specified

by ebarcza 7/23/2012 6:38:00 AM

This works:

setup.exe /Action=Install /INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server" /INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server" /INSTANCEDIR="C:\Program Files\Microsoft SQL Server"

Tags:

SQL SERVER

Access is denied when attaching a database

by ebarcza 4/12/2012 11:32:00 AM

If you get an Access is Denied error when attempting to attach an MDF file, just start SQL Management Studio as an administrator and try again.

BOOM - database attached!

Solved the issue for me!

Tags:

SQL SERVER

SQL Server validating overlapping dates, date ranges

by pencilvac 4/11/2012 5:55:00 AM

When saving records to your database you may find that you cannot allow users to save multiple similar records with overlapping date ranges. The way I went about doing this was to check for the overlap in a SQL stored procedure in SQL server.

ALTER PROCEDURE [dbo].[UpsertGroupFieldValues]
    @GroupFieldValueID int = -1,
    @TargetEntityID int,
    @TargetPKID int,
    @PKID int,
    @EntityID int,
    @GroupFieldID int,
    @StartDate DateTime,
    @EndDate DateTime,
    @UserID int,
    @GroupValueIDReturned int OUTPUT

Out of all of these parameters If these parameters match a record that is already in the database, but without overlapping dates then we are good to save it. If however, the fields do match a record already in the database WITH overlapping dates, then we cannot save the record and we need to alert the user with an error.

To check for overlap I used an IF statement with a NOT EXISTS:

                //Check if there is a similar record (matching fields) with overlapping dates.//

                IF NOT EXISTS(select * from GroupFieldValues
                            WHERE TargetEntityID = @TargetEntityID
                            AND TargetPKID = @TargetPKID
                            AND PKID = @PKID
                            AND EntityID = @EntityID
                            AND GroupFieldID = @GroupFieldID
                            AND (
                                    (@StartDate BETWEEN StartDate AND EndDate)
                                    OR (@EndDate BETWEEN StartDate AND EndDate)
                                    OR(@StartDate <= StartDate AND @EndDate >= EndDate)
                                )


                   )                           

    --Basically we have a similar record. If we do have a similar record lets see if their dates overlap. If the parameter startdate is between the records start and end then it must be overlapping. If the parameter endDate is between the records start and end then it has to be overlapping. Otherwise the only other situation I can think of is if the parameter startdate is before the records startdate and the parameter @EndDate is after the records EndDate which means overlap. If this does not exist then we can go ahead and save the record.


                         
                BEGIN
                           YOUR INSERT STATEMENT
                END
                If it does exist ( an overlap) then we raise an error.
                ELSE
                    BEGIN
                        RAISERROR('Your new grouping was not saved because a similar group already exists within the same date range.',18,1)
                        --Print'Date Confliction'
                    END

ANOTHER TOPIC OF INTEREST: If you are doing an upsert stored procedure aka you are either inserting a new record or updating an already exisitng record with the same SPROC you will have to do a separate Date overlap test. Think of this situation: Your user goes into edit mode of a record in the front end of your application or website. The user changes the end date value to be November instead of October. When you check for overlap with the process above, the check will fail because there is a record with overlapping date ranges and your parameters (The record itself you are trying to update!). A way to get by this is performing separate checks based on whether you are trying to update or insert. Example:

 

IF @GroupFieldValueID = -1 --(our primary key) aka you are trying to insert a new record since its -1 (otherwise this will be the ID of the record you want to update)
    BEGIN --run our check for the new record
                IF NOT EXISTS(select * from GroupFieldValues
                            WHERE TargetEntityID = @TargetEntityID
                            AND TargetPKID = @TargetPKID --The company
                            AND PKID = @PKID --specific Value of contract, Location, Pipeline, Pricing Area from Drop downs.
                            AND EntityID = @EntityID --Entity were grouping on IE Pipeline or Contract
                            AND GroupFieldID = @GroupFieldID
                            AND (
                                    (@StartDate BETWEEN StartDate AND EndDate)
                                    OR (@EndDate BETWEEN StartDate AND EndDate)
                                    OR(@StartDate <= StartDate AND @EndDate >= EndDate)
                                )
                           
                            )   
                BEGIN
                        --PRINT'Start if no date confliction'

                               YOUR INSERT STATEMENT
                       
                END
               
                ELSE
                    BEGIN
                        RAISERROR('Your new grouping was not saved because a similar group already exists within the same date range.',18,1)
                        --Print'Date Confliction'
                    END
                   
                   
    END   
    ELSE--if @GroupFieldValueID != -1 meaning we are trying to update a record
        BEGIN --run a slightly different check where we specify that we are looking for an overlapping record that is NOT this record (AND GroupFieldValueID != @GroupFieldValueID)
            IF NOT EXISTS(select * from GroupFieldValues
                            WHERE TargetEntityID = @TargetEntityID
                            AND TargetPKID = @TargetPKID --The company
                            AND PKID = @PKID --specific Value of contract, Location, Pipeline, Pricing Area from Drop downs.
                            AND EntityID = @EntityID --Entity were grouping on IE Pipeline or Contract
                            AND GroupFieldID = @GroupFieldID
                            AND (
                                    (@StartDate BETWEEN StartDate AND EndDate)
                                    OR (@EndDate BETWEEN StartDate AND EndDate)
                                    OR(@StartDate <= StartDate AND @EndDate >= EndDate)
                                )
                            AND GroupFieldValueID != @GroupFieldValueID
            )
                BEGIN
                      YOUR UPDATE STATEMENT
                END
            ELSE
                BEGIN
                    RAISERROR('Your Group was not updated because there is another group with overlapping date ranges. ',18,1)
                END
        END   
END

 

BOOOM no more conflicting date ranges.

SQL Server Trigger Columns Updated

by ebarcza 11/10/2011 7:00:00 AM
This handy dandy little function will return a table with all the columns that were updated in a trigger.
CREATE FUNCTION [dbo].[udf_GetUpdatedColumns]( 
@Tablename VARCHAR(100), @ColumnsUpdated VARBINARY(255) ) 
RETURNS TABLE 
AS 
RETURN 
    SELECT 
        COLUMN_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS Field 
    WHERE 
        TABLE_NAME = @Tablename 
        AND sys.fn_IsBitSetInBitmask( @ColumnsUpdated,
            COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), 
            COLUMN_NAME, 'ColumnID')) <> 0

Usage is as follows:

ALTER trigger [dbo].[trg_InfoUpdate] on [dbo].[Info] for  update
as
print 'TRIGGAH'
DECLARE @ColumnsUpdated VARBINARY(1000) = COLUMNS_UPDATED()
SELECT * FROM dbo.udfDecodeBitmask('BankingInfo', @ColumnsUpdated)

Tags: , ,

SQL SERVER

Overriding AspNetSqlMembershipProvider in ASP.NET 4.0

by rbellantoni 11/8/2011 7:45:00 AM

If you are having as much trouble as I did figuring out where the hell all the web.config settings went after creating Users and Roles using the built in administration tools in .NET then read on!

It turns out, that in ASP.NET 4.0, they removed some of the "clutter" from the web.config since some web.configs were getting very large with configurations and developer added keys etc. So they moved it to a machine.Config file inside of the framework folder. What this means is that they took out all the standard settings in the web.config that are required to run a website so you don't have to see them anymore....HOWEVER, they ALSO moved the default membership provider settings as well. So what does this mean?  It means you can't just make a tweak to the default settings, you need to actually implement your OWN web.config provider as follows:

 <membership>
            <providers>
                <clear/>
                <!--<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" 
                 enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"
 passwordAttemptWindow="10" applicationName="/"/>-->
                <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" 
connectionStringName="test" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="500" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
            </providers>
        </membership>
        <profile>
            <providers>
                <clear/>
                <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
            </providers>
            <properties>
                <add name="DisplayName"/>
            </properties>
        </profile>
        <roleManager enabled="true">
            <providers>
                <clear/>
                <add connectionStringName="test" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"/>
                <!--<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"/>-->
                <add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider"/>
            </providers>
        </roleManager>

Now you can go ahead and change the settings as necessary.

Tags:

.NET | ASP.NET Enterprise Library | SQL SERVER

SQL Server Function to Get number of Days in month

by ebarcza 11/4/2011 10:12:00 AM
CREATE FUNCTION [dbo].[fn_GetDaysInMonth] ( @pDate    DATETIME )
RETURNS INT
AS
BEGIN
    RETURN CASE WHEN MONTH(@pDate) IN (1, 3, 5, 7, 8, 10, 12) THEN 31
                WHEN MONTH(@pDate) IN (4, 6, 9, 11) THEN 30
                ELSE CASE WHEN (YEAR(@pDate) % 4    = 0 AND
                                YEAR(@pDate) % 100 != 0) OR
                               (YEAR(@pDate) % 400  = 0)
                          THEN 29
                          ELSE 28
                     END
           END
 
END

Tags:

SQL SERVER

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About the author

Name of author Author name
Something about me and what I do.

E-mail me Send mail

Calendar

<<  September 2017  >>
MoTuWeThFrSaSu
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

View posts in large calendar

Recent comments

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017

Sign in