How to write database creation scripts when coding software setup? A SQL Server database is part of an software application that clients will install. 

When the clients are installing the software, the setup process needs to create an empty database.

Do I need to manually start figuring out which tables needs to be created first, and which foreign key needs to be referenced after X table is created? Or is there a tool that creates these scripts in the correct order using the existing database?
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.