I tried get result of "Script Table as Create To Query" by a SQL Query for my tables.
It is like Right click on table->Script Table as ->Create To->Query on SQL Management Studio
I have this query :
declare @vsSQL varchar(8000)
declare @vsTableName varchar(50)
select @vsTableName = 'dbo.TableName'
select @vsSQL = 'CREATE TABLE ' + @vsTableName + char(10) + '(' + char(10)
select @vsSQL = @vsSQL + ' ' + sc.Name + ' ' +
st.Name +
case when st.Name in
('varchar','varchar','char','nchar','nvarchar') then '(' +
cast(sc.Length as varchar) + ') ' else ' ' end +
case when sc.IsNullable = 1 then 'NULL' else 'NOT NULL' end + ',' + char(10)
from sysobjects so
join syscolumns sc on sc.id = so.id
join systypes st on st.xusertype = sc.xusertype
where so.name = @vsTableName
order by
sc.ColID
select substring(@vsSQL,1,len(@vsSQL) - 2) + char(10) + ')
Result of Query :
CREATE TABLE TableName (
Id int NOT NULL,
Name nvarchar(-1) NULL,
Code int NULL,
Adress nvarchar (200) NOT NULL
)
But my query can not take nvarchar(max).It show nvarchar(-1)
How can change my query for to be like this :
Chage nvarchar(-1) to nvarchar(max)
CREATE TABLE TableName (
Id int NOT NULL,
Name nvarchar(max) NULL,
Code int NULL,
Adress nvarchar (200) NOT NULL
)
You have this line in the code:
cast(sc.Length as varchar)
Change it to:
(case when sc.length < 0 then 'max' else cast(sc.Length as varchar(255)) end)
Notice that I also added a length parameter to varchar()
. Always specify a length when you use the type. When the default length is not long enough for what you are doing, finding the problem is really hard.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.