tsql - T-SQL Error: Incorrect syntax near '+' -



tsql - T-SQL Error: Incorrect syntax near '+' -

i wanna create db, want read instancename since i'm using instance name folder name wrote code as:

set @instancename = convert( varchar(50),serverproperty ('instancename')) if @instancename null begin set @instancename= 'mssqlserver' -- mssqlserver if default instance end declare @sql varchar(128) set @sql= 'create database [dpo_maindb] on primary ( name = n''dpo_maindb_data'', filename= n''h:\'+@instancename+'\sqldata\dpo_maindb_data.mdf'', size = 4mb , maxsize = unlimited, filegrowth = 10%) log on ( name = n''dpo_maindb_log'', filename = n''g:\'+@instancename+'\sqllogs\dpo_maindb_log.ldf'' , size = 2048kb , maxsize = unlimited , filegrowth = 10%) end' exec(@sql)

but got error: wrong syntax near '+'.

i tried many things still have problem. know can utilize + since i've used before dunno what's wrong :( i'll appreciate help !

you need using dynamic sql. create sql want execute in variable , pass variable exec. like:

set @sql = 'create database [dpo_maindb] on primary ( name = n''maindb_data'', filename= n''h:\'+@instancename+'\sqldata\dpo_maindb_data.mdf'', size = 4mb , maxsize = unlimited, filegrowth = 10%) log on ( name = n''maindb_log'', filename = n''g:\'+@instancename+'\sqllogs\dpo_maindb_log.ldf'' , size = 2048kb , maxsize = unlimited , filegrowth = 10%) end' exec(@sql)

you able reference variables no problem in @sql assignment. notice have escaped ' characters '' within of @sql variable.

sql tsql

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -