How to write database creation scripts when coding software setup?
Well, you can always generate a script of the current database using right-click > Tasks > Generate Scripts in Object Explorer (this should create the tables and keys in the right dependency order). Or you could generate such a script with a 3rd party tool like Red Gate SQL Compare1 by comparing the current version of your schema against an empty database. Or you could ship a .bak file (a backup of an empty copy of your database) with your software and the setup could restore it.

1. Probably dated now, but a few years ago I blogged about many alternatives here.