Sql server will not let you dropa table if it has default contraints (like default values for columns.)
This script will let you find them.
1. Determine the constraint name.

if object_id('[dbo].[GetDefaultConstraintName]') is not null
    drop function [dbo].[GetDefaultConstraintName]
go

create function [dbo].[GetDefaultConstraintName] (
    @TableName varchar(max),
    @ColumnName varchar(max))
returns varchar(max)
as
begin

    -- Returns the name of the default constraint for a column

    declare @Command varchar(max)
    select 
        @Command = d.name
    from 
        ((
        sys.tables t join
        sys.default_constraints d
            on 
                d.parent_object_id = t.object_id) join
        sys.columns c
            on 
                c.object_id = t.object_id and 
                c.column_id = d.parent_column_id)
    where 
        t.name = @TableName and 
        c.name = @ColumnName
    return @Command
end
go

2. Generate dynamic sql to drop the constraint. Assume that the table name is MyTable and the column name is MyColumn.
execute ('alter table MyTable drop constraint '+
           [dbo].[GetDefaultConstraintName]('MyTable','MyColumn'))

3. Re-create the constraint with the desired default value. Assume that the new default value should be 33.
alter table MyTable add constraint [DF_MyTable_MyColumn] default (33) for MyColumn
1

View comments

  1. I live in a relatively quiet town of Piscataway in New Jersey.  The township is mostly blue.  Which means that anyone running on a democratic ticket is most likely to win.

    The mayor of this township is running for the 6th term.  Most people in the township are not happy with this mayor's leadership, yet he keeps winning.  It's not like there is a shortage of well qualified folks for this post.  So, how does he do that?  The answer is simple.  Once he wins the democratic primary, he might as well open the champagne bottle in July.

    This is where the rigging comes into play.  Note that nothing is illegal about it, but it should be.  This is how the democratic primary ballot for 2020 looks like.





    Obviously, all the candidates are democrats.  However, column B sticks out more because of stalwart names like Vice President Biden, Senator Booker, and Congressman Pallone.  This visual association gives Mayor Wahler an undue advantage over his opponents.  Take a look at the visuals below and tell me which path looks less complicated to a human brain.




    0

    Add a comment

  2. I have been using Crystal Reports to create crappy looking reports in my VB (yes, many many years ago,) VB.Net, and C# apps.  I like it because I know it well and it is functional for the most part.  However, every new version of Crystal Reports brings in a lot of new headaches.  I have been maintaining an application which was kept as 32 bit app primarily because of Crystal Reports.  So, this weekend, I decided to try to convert the app to 64 bit anyway.

    My original environment was:
    C# .Net 3.5 framework
    Crystal Reports designed in XI
    Reports use an Access MDB file with linked tables to various data sources.

    I upgraded the environment to:
    C# .Net 4.0 framework
    Crystal Reports designed in XI
    CR Run time upgraded to 13.0.4000.x.
    CR for visual studio also upgraded to 13.0.26.x.
    Reports still use an Access MDB file with linked tables to various data sources.

    The original code to switch the Access database was as following:
        string reportFile = "AppReport.rpt";
        var rep = new ReportDocument();
        rep.Load(reportFile);
        rep.Database.Tables[0].Location = @"c:\temp\run-rime-access.mdb";
        crystRep.ReportSource = rep;
    
    
    Things worked as expected when I compiled the code explicitly as 32 bit (X86 mode.)  64 bit exe simply would not run with a variations of errors as followng:

    Exception thrown: 'System.Runtime.InteropServices.COMException' in CrystalDecisions.CrystalReports.Engine.dll
    An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in CrystalDecisions.CrystalReports.Engine.dll
    Error in File AppReport 11476_6424_{59713F00-ED10-4E5B-928E-1D8AC1A7832B}.rpt:
    Failed to load database information.
    

    I googled and surprisingly did not find any solutions, which worked for me. I tried the uselegacyv2runtimeactivationpolicy attribute in app.config and/or assembly directives as suggested by SAP and StackOverflow posts, to no avail.
    
    At this time, I also felt that it will be good idea to convert the mdb file to accdb, later editions of Microsoft Access database.  Surprise, this version of Crystal still does not give a choice to connect to accdb, Access files.  So, I started looking into ODBC connection options.  I finally got it to work in 64 bit environment.

    Here is what you need to do make all this work.

    1. Install CR for visual studio on your development machine.  It's free.  It's the same version for 32 and 64.
    2. Install CR 64 bit run time on the development machine.  It is available for free at SAP site. You can install 32 bit run time at the same time.
    3. Install 64 bit ACE Driver on your development machine.  You cannot install 64 bit driver at the same time.  If you have 64 bit office installed on your machine, the installer will not even let you install 32 bit ACE driver.
    4. Here comes the hard part.  You have to design you report using a 32 bit data source.  As you can see if you do not have 32 bit ACE driver installed on your machine, you can not create a DSN for it.  Crystal Reports does offer support for accdb natively.  I overcame this issue by using a mdb version of the same access database.  Look at the screenshot below.  You can see that I have a dsn ash-lab-64bit, which uses 64 bit ACE driver.  However in Crystal Reports designer I only see ash-lab-32bit dsn, which uses natively supported mdb (DAO) driver in Crystal Reports.

    Good so far!  You have designed the report using a 32 bit ODBC DSN.  At run time we need to change this DSN to a DSN less connection.

    C# Code to make it all work in 64 bit run time environment:

    1. Get rid of  uselegacyv2runtimeactivationpolicy attribute from app.config.
    2. Use the following code if you still like DSN based connections.  Keep in mind that every client will need this connection on his/her machine.

       string reportFile = "Example3.rpt";
       var rep = new ReportDocument();
       rep.Load(reportFile);
       ConnectionInfo tConnInfo = new ConnectionInfo();
       tConnInfo.DatabaseName = @"c:\temp\__run-time.accdb";
       tConnInfo.ServerName = "ash-lab-64bit";
       tConnInfo.Password = "";
       foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in rep.Database.Tables)
       {
        crTable.LogOnInfo.ConnectionInfo = tConnInfo;
        crTable.ApplyLogOnInfo(crTable.LogOnInfo);
       }
       crystRep.ReportSource = rep;
      
      
    3. Use the following if you like DSN less connection.  This is what I prefer.

       string reportFile = "Example3.rpt";
       var rep = new ReportDocument();
       rep.Load(reportFile);
       rep.DataSourceConnections[0].SetConnection(@"DRIVER=Microsoft Access Driver (*.mdb, *.accdb);UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL=MS Access;DriverId=25;DefaultDir=C:\temp;DBQ=C:\temp\__run-time.accdb","",false);
       crystRep.ReportSource = rep;
      
      
    4. Compile your code with "ANY CPU" or 64 bit setting.

    Software do you need to make it work on the client machine:

    1. Crystal report 64 bit run time, available for free at SAP site.
    2. Microsoft's 64 bit ACE driver.
    0

    Add a comment

  3. Sorry Mac folks, this article is very Windows specific, however, it is worth a read.  How many times it has happened to you that you had to look for a recipe you used or a code snippet you wrote several years ago.  That's easy, you say.  You have a clever folder structure for organizing documents and you put your recipes and code snippets buried in those folders.  You have a crafty search program like Agent Ransack, which goes through your files in a second and find the content you were looking.  Actually for tools like Agent Ransack, you don't even have to organize your files in folders.  It will find whatever you are looking by searching the file name or its content.  This will work, provided you always have access to your laptop.  Other than the accessibility, the file model needs a lot more to be desired.

    In the past I used digital post it notes for this purpose.  The easiest one was to maintain the notes in Outlook.  The notes were synchronized to my iPhone, and the life was great.  For reasons unknown to me, Apple decided to remove this sync option, forcing me to use iCloud notes.  It works, I can read these notes from my iPhone as well as from a web browser, and they sync well.  My pet peeve with iCloud site is that it takes so long to load.  The two factor authentication kicks in whenever it feels like it.  The searches don't work right.  Besides, who is to say that Apple will remove the Notes feature completely, in future.  There are commercial options like Evernote.  First of all, the idea of paying a monthly fee for the rest of your life for post it notes, is crazy.  Secondly, one day Evernote may get bought out by, say Facebook, and Facebook decides that it does not fit into their social media model, and kill the product.  The bottom line is that you have to take matters into your own hand and take control of your own content.  In the next sections I will show you how you can do this with little to no cost.

    I implemented a wiki solution for my need.  The best example of a wiki software is Wikipedia, which is essentially maintaining web pages without using any special web authoring tools.  Of course a wiki software is about collaboration too, but in our use case, we won't be using it.

    Choosing a wiki software

    There are so many free open source wiki engines available.  All of them are more than adequate for our need.  I wanted the software to be simple and lightweight.  I specifically looked for plain text files based wiki software.  The two top contenders were:
    TiddlyWiki is a JavaScript based wiki with just one file.  Everything is stored in this file.  If you have only very small amount of information to be stored, this solution will work for you fine.  You can copy this file to your iPhone or host it somewhere for ready access.

    I chose DokuWiki, because I have literally thousands of notes, with code snippets, recipes, random writings, and account numbers etc.  I needed them to be in separate files and readily searchable.  DokuWiki can create a custom installation package for you with only the components you need.

    Download DokuWiki


    Go to the download link.

    Select the stable version.


    Make sure you check MicroApache (Windows) checkbox.

    This makes a micro web server to be included in the package.  Remember, there is no need to install PHP or anything else.

    Remove unwanted languages from the package

    Skip the plugins in the initial install.

    Unzip the installer package

    The installer package may not be in .exe or .msi format, that you can double click on it and execute it.  It may be in .tgz format.  Install 7Zip utility to unzip the .tgz files.  You may want to extract DokuWikiStick folder from the zip file and run run.cmd.



    Configure DokuWiki

     
    Follow the instructions.  You will be asked to rename dokuwiki\install.php file, after configuration is done.  Note that nothing really gets installed (You have love the Unix folks for that.)  You start the Apache webserver using run.cmd only, and your Wiki is up and running.  You can access it through a web browser.  You can always tweak the port it runs.  Note that you have to run run.cmd, to start DokuWiki server, every time you login to your machine.  If you are like me, you may want to configure it to run as a service.

    Configure DokuWiki to auto-start as a service

    • Download WinSw from GitHub.
      Try not to build the solution yourself.  I got ton of errors. Try to get the pre-built exe if you can.
    • Copy WinSw.exe to the same folder where run.cmd exists.
    • Rename WinSw.exe to dokuwiki.exe (You can pick any name.)
    • Create an xml file, dokuwiki.xml (the name must match with the exe in the prior step.)

    In our example run.cmd resides under c:\DokuWikiStick.
    • Open command prompt in Admin  mode and run the following command from the location where run.cmd is residing.
      dokuwiki install –overwrite
    • Fix the permission on the c:\DokuWikiStick folder so that this service can read and write to files in this folder.  EveryOne full control is fine, if you are the only user on your machine.

    Access from iPhone or iPads on your LAN

    This Wiki is not accessible from the Internet.  However, it is not a hard task.  With a port forwarding on your router, you can set this up for access from outside.  Having said that, I would say, try not to do it if you have a lot of sensitive information on this site. 

    If you want to access the Wiki within your LAN or Wifi Network from iPhone or iPad, make sure you use the .local suffix after the host name in the url.

    After your DokuWiki is ready.  Learn the basic syntax and you are on your way to being organized by creating bite size post it notes to yourself.  Remember, there is nothing wrong or right about how you want to organize the content.  Just remember to put as many tags in your content so that you can search it later with ease.  Take frequent backup of the DokuWikiStick folder and you will have your content for the rest of your life.

    Happy organizing!
    0

    Add a comment

  4. This is my first blog of 2016.  I think 2016 will be an exciting year for the world.

    On a different note, the Powerball lottery's jackpot is a record $800 million.  My luck with any kind of gambling has been consistently very bad.  I do not win raffles, football pools etc.  I lose in casinos, and of course in the lottery.  I have accepted it as a positive thing, so I try to stay away from lottery or any gambling activity as much as possible.  In my office they collected $10 each in a pool of some 30-40 people, for last week's jackpot, which was $400 million.  The tickets were purchased, scanned, and emails were sent out to all the contributors.  To be in the team spirit, I contributed too.  Of course, we did not win.  So, they started again today to collect for the bigger jackpot.  This time I decided to not be a team player.  I am sure the same routine was played out in almost every workplace in America.

    So, here is my question:  why doesn't the government give out more prizes in smaller chunks?  Say, $100,000 to 8000 people? I know the answer already.  The government collects more taxes on $800 million prize than on $100,000.  I get it.  So, let us make it $1 million, to 800 winners.  I am sure the taxes at $1 million and $800 million will probably be in the same bracket.  At least, it will make 800 parties happy.  Hey, for all you know, I might even join every lottery pool!
    1

    View comments

  5. Now that I was somewhat comfortable using Git for version control, I immediately felt the need to create some private repos. I needed a remote repository to backup my work. One option was to get a paid account with the good folks at the GitHub, or use my Linux hosting package at 1&1. I chose the later. I use GIT for Windows. By the way, Git already comes installed on the Linux servers on 1&1. I wanted to use a secured connection to the server. So, here are the steps to create a secured remote repository on a Linux server, hosted at 1&1.  Keep in mind that these instructions are primarily for Git for Windows client, however, they can be used for other clients as well with subtle differences in the folders etc.  I am sorry for being over-detailed, but one of these small missteps get you from being successful.
    1. Make sure you have ssh access to the server.  You can get the information from your 1&1 control panel.  Test it using the popular ssh client, Putty.
    2. On you Windows machine, get the location of Git for Windows.
      You will see folders like:
      C:\Users\{User}\ AppData\Local\GitHub\PortableGit_{guid}\bin
      C:\Users\{User}\AppData\Local\GitHub\PortableGit_{guid}\cmd
      Example:
      C:\Users\bender\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin
      Bender is my windows login.
    3. Add both folders to your path. See below.
    4. Test the prior step by typing the following in a command prompt.
      git --version
      
    5. Create folder .ssh under:
      rem Fix the folder name to suit to your environment.
      md C:\Users\{User}\AppData\Local\GitHub\PortableGit_{guid}\.ssh
      
    6. Open a command prompt, switch to this .ssh folder, and run the following commands.  For now do not choose a pass phrase for the private key.
      cd C:\Users\{User}\AppData\Local\GitHub\PortableGit_{guid}\.ssh
      rem Generate the private and public keys.
      ssh-keygen -t rsa
      rem This step will ask for pass phrase to encrypt your private key.
      rem For now just hit enter to skip.
      rem Pass phrase should be used, however, it requires extra steps to avoid
      rem being prompted for it every time you interact with the repo.
                  
    7. The ssh-keygen step, would create private and the public keys as id_rsa and id_rsa.pub.
    8. Ftp id_rsa.pub to the 1&1 server to .ssh folder under your home folder.  If you are not sure just ftp it to some place on the server.
    9. Log into the 1&1 server using Putty and type the following commands:
      # Switch to home folder
      cd ~
      # Create .ssh folder undre home folder. 
      # It may give error, if one exists already. 
      # No problem. Just proceed.
      mkdir ~\.ssh
      # Add contents of id_rsa.pub to authorized_keys file under .ssh folder.
      # This is the same file which you Ftp-ed to the server.
      cat id_rsa.pub >> ~\.ssh\authorized_keys
      # Verify if authorized_keys exists.
      ls -al ~/.ssh/authorized_keys
      # Create a folder to hold your remote repos.
      mkdir ~/gitrepos
      # Create your first repository (mylabs)
      mkdir ~/gitrepos/mylabs
      cd ~/gitrepos/mylabs
      git init --bare
      # You are done with the server for now.
      
    10. Come back to the Windows machine.  Open a command prompt and test your ssh connection using the private key.  In my example below, 1&1 user id is u1234567 and my hosted domain is xyz.com.
      ssh u1234567@www.xyz.com ls
      # If all goes well, you should see the directory listing from 1&1 server.
      # If that happens you are ready to use the remote repo.
      
    11. Create a local repository.  In my example the location is c:\mylabs.
      cd c:\mylabs
      git init
      rem Add all existing files and folders to the repo.
      git add .
      rem Commit the newly added files.
      git commit -m "My first commit, hurray!"
      rem Add the 1&1 server as a remote server with alias origin.
      git remote add origin ssh://u1234567@www.xyz.com/~/gitrepos/mylabs
      rem Sync the commited changes to 1&1 server
      git push --set-upstream origin master
      # set upstream is required only for the first time.
      # Because you are pushing the changes to a blank repo on the server.
      # Future sync would be as following:
      git push origin master
      
      
    12. You can test your prior step by cloning the repo from 1&1 server to c:\temp folder.
      cd c:\temp
      git clone ssh://u1234567@www.xyz.com/~/gitrepos/mylabs
      rem You will see files and folders in c:\temp\mylabs folder.
      
    Happy coding!!
    16

    View comments

  6. In 2011, I blogged about my experiences with the cheap hosting providers like GoDaddy and 1and1 Hosting.  In the blog I mentioned that 1and1 hosting's SQL panel allows you to run SQL DDL statements using dynamic SQL only.  All creates, drops, grants etc. must be issued using EXEC() statements.


    This is how a developer creates the sql code:
    if object_id('dbo.GetJustDate') is not null
     drop function dbo.GetJustDate
    go
    
    create function dbo.GetJustDate(
     @Date datetime) returns datetime 
    as
    begin
     declare @Ret datetime
     set @Ret=convert(datetime,convert(varchar,@Date,106))
     return @Ret
    end
    go
    
    grant execute on [dbo].[GetJustDate] to olgauser
    go
    


    1and1's SQL control panel expects it in the following way:
    exec ('if object_id(''dbo.GetJustDate'') is not null
     drop function dbo.GetJustDate
    ')
    exec ('create function dbo.GetJustDate(
     @Date datetime) returns datetime 
    as
    begin
     declare @Ret datetime
     return @Ret
    end
    ')
    exec ('grant execute on [dbo].[GetJustDate] to olgauser
    ')
    


    As you can see that converting all your sql code in the dynamic SQL format can be tedious. Well, I have made the job easier for you. My 1&1 Formatter utility would read all your sql scripts from a folder and create an output file in the expected format.

    The only requirement is that all your sql statements must be split in separate batches using "Go" statements.  The utility currently supports create procedure, create function, "if object..", and grant statements.  However, you can add support for more statements using the regular expression provided in the config file.

    How to use:
    1. Download the utility and unzip the contents in any folder.  No installation is necessary.
    2. Open the 1and1Formatter.exe.config in a text editor.  Configure the following keys:
      convertTabToSpaces: When > 0, tabs will be converted to as many spaces.
      inFolder: Location of all .sql files needing conversion.
      outFile: Output file title.
      sqlPatterns: Regex pattern to identify the code.  Tweak it carefully.  I have used two named groups, codeBegin and codeBody.  Make sure your changes populate these groups, as they get concatenated in the formatting process.
    3. Run the program using Explorer or the command prompt.
    Please report bugs to support@ipcolony.com.
    0

    Add a comment

  7. As you know, this series is dedicated to those individuals whose work makes me feel insignificant, and my existence, meaningless.

    I love Sudoku.  If I was to put these puzzles into easy, medium, hard, and expert categories, I can deal up to hard level, comfortably.  Now the question is, what makes a hard puzzle, hard.  You may think that it is the number of count of pre-solved numbers make it so.  Unfortunately, I have seen cases where a hard puzzle had more initial numbers than a medium one.  I also wrote a program to solve the Sudoku puzzle using some brute force, by generating all possible combinations of the solution based upon the initial hints provided.  In this method it did not matter to the program, whether the puzzle was easy, medium, or hard etc.

    So, once again, what makes a puzzle hard to us.  Apparently this team of students from the University of Washington wrote this paper on the mathematics of Sudoku.  Almost none of it makes sense to me, a mathematically challenged person, yet it makes me feel to go back and hide in my little shell.

    So, kudos to the Team2280 from the University of Washington for explaining the math behind the Sudoku puzzles.
    0

    Add a comment

  8. Back in February 2013, I started a series dedicated to outstanding individuals, whose accomplishments simply dwarfs our own.  In this blog I have chosen this honor to go to Jeremy Kun, a mathematics PhD student.

    What possible connection could be there between the movie, The Lord of the Rings and fast Fourier transform?  You can find the answer on Jeremy Kun's website.

    So, Jeremy, we are not worthy!!
    0

    Add a comment

  9. Around 1987, I was working downtown in New York City.  I started going to a local Irish pub to get my lunch (Not to be confused with beer.)  They served this wonderful dish called the corned beef.  I did not know how it was prepared but I just loved it.  A few years later I was introduced to pastrami, which I think, is a close cousin of the corned beef, I loved it even better.

    Over the years, I have gotten very good at making the corned beef from scratch.  However this was my first attempt to make pastrami.  The recipe is not original and I got it by watching a YouTube video.  I cheated a bit I actually did not make pastrami from scratch like my corned beef.  I actually used a corned beef brisket, they sell almost all the time at Costco.  If you get the corned beef brisket from Costco, do NOT use the spices which come with it.

    So, what exactly is a corned beef brisket?  The process of corning is basically to soak the meat in brine (salt water) for a few days.  In every recipe there is one secret ingredient which makes all the difference.  In case of pastrami and corned beef, it is the pink salt, which gives the final product a nice pinkish/reddish texture.  It is hard to find it at the grocery stores.  I found it at mySpiceSage.com.  Look for Prague powder number 1.

    1. Skip this step if you already got corned beef brisket from Costco.
      Use this recipe for a 5 lbs brisket.
          a. One gallon water
          b. Two cups Kosher salt
          c. Five teaspoons pink salt
          d. 1/2 cup brown sugar
      Bring the water to a boil with all the ingredients above.  Once cooled, put the brisket in a pan soaked in this brine for at least five days.  Make sure to keep it in a cool place or refrigerator.
      The end product is a corned beef brisket.
    2. This is where the recipe for pastrami starts.
      You will need the following spices:
          a. 1 tbsp of red pepper
          b. 2 tbsp of black pepper
          c. pepper flakes to your taste
          d. 2 tbsp of coriander powder.  Indian grocery stores carry it for a great price.
      Red Pepper

      Pepper Flakes

      Black Pepper

      Coriander Powder
      3. Prepare the meat.Remove excess fat.  Pastrami, unlike the corned beef has very little fat.
      Remove Excess Fat


      Aluminum foil oiled
      4. Sprinkle the spices one by one on the brisket on both sides and rub them thoroughly.  Use the black pepper as the last spice to create that nice blank black peppery edge.

      Rub Spices

      Rub Spices

      Rub Spices

      Rub Spices
      5. Wrap the meat in aluminum foil, six times (yes, no kidding.)  We want the juices to be locked in.
      Wrap meat in the foil


      Wrap it again

      Wrap it six times
      6. Put the foiled meat in the oven at 250 degrees for five hours to cook.

      7. After five hours let the meat sit for another day.  This is very important.

      8. Open the foil, carve the meat into slices to your liking and enjoy.
      The final product

    1

    View comments

  10. With this post, I am starting a new segment called, "We are not worthy!"  The segment is essentially to honor ordinary people who create.  When I see the creativity of such people, it makes me humble and I simply want to say, "I am not worthy!"  Let me make something clear, I will never consider Arianna Huffington and Deepak Chopra for this honor, in spite of their accomplishments.  That is a topic for another day.

    After my wife banned me from doing any woodworking activity in the garage, I was looking for some alternatives, like building a woodworking shed etc.  A few googling  attempts landed me to Kevin Brady's woodworking site about how he built a woodworking shop from scratch in his back yard.  I looked at everything this guy had done in the past, and he has done a lot.  The remarkable quote which caught my attention on his site was, "Stuff That Matters!"  It says it all.  Kevin does it all, not for fame, not for money, he does it because he loves doing it.

    So, this segment of "We are not worthy" is dedicated to Kevin Brady!  Kevin, thanks for sharing your creativity with the rest of us.
    1

    View comments

About Me
About Me
My Photo
Piscataway, New Jersey, United States
I am an electrical engineer by education and a software developer by profession. I like building electro-mechanical models. I also like grilling and barbecuing with passion. To burn my beer cals, I swim and run. I usually post my DIY projects on: http://www.instructables.com/member/kabira/
Blog Archive
Loading
Dynamic Views theme. Powered by Blogger.