Amir Mirkamali RSS 2.0
 Sunday, December 04, 2011
declare 

@NewCollation varchar(255)

,@Stmt nvarchar(4000)

,@DBName sysname

set @NewCollation = 'SQL_Latin1_General_CP1256_CI_AS' -- change this to the collation that you need

set @DBName = DB_NAME()

declare 

@CName varchar(255)

,@TName sysname

,@OName sysname

,@Sql varchar(8000)

,@Size int

,@Status tinyint

,@Colorder int

declare curcolumns cursor read_only forward_only local

for select

QUOTENAME(C.Name)

,T.Name

,QUOTENAME(U.Name) + '.' +QUOTENAME(O.Name)

,C.Prec

,C.isnullable

,C.colorder

from syscolumns C

inner join systypes T on C.xtype=T.xtype

inner join sysobjects O on C.ID=O.ID

inner join sysusers u on O.uid = u.uid

where T.Name in ('varchar', 'char', 'text', 'nchar', 'nvarchar', 'ntext')

and O.xtype in ('U')

and C.collation != @NewCollation

and objectProperty(O.ID, 'ismsshipped')=0

order by 3, 1

open curcolumns

SET XACT_ABORT ON

begin tran

fetch curcolumns into @CName, @TName, @OName, @Size, @Status, @Colorder

while @@FETCH_STATUS =0

begin

set @Sql='ALTER TABLE '+@OName+' ALTER COLUMN '+@CName+' '+@TName+ isnull ('('

+CASE @Size WHEN -1 then 'max' else convert(varchar,@Size) end+')', '') +' COLLATE '+ @NewCollation

+' '+case when @Status=1 then 'NULL' else 'NOT NULL' end

--exec(@Sql) -- change this to print if you need only the script, not the action

PRINT @Sql

fetch curcolumns into @CName, @TName, @OName, @Size, @Status, @Colorder

end

close curcolumns

deallocate curcolumns

commit tran
Sunday, December 04, 2011 8:18:44 AM UTC  #    -
SQL Server | Troubleshooting
 Wednesday, December 29, 2010
When you save a table in Management Studio that requires the table be dropped and recreated behind the scenes, the change will fail by default with the below warning.

In SQL Server, tables are dropped, recreated and reloaded automatically for you without having to worry about what's going on behind the curtains but this may create issues for some users. This behavior is required upon a number of actions but most common is creating a new column in a specific location in the table.

Warning Message:

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

To fix this in Management Studio, go to Tools -> Options then go to the Designer Page and uncheck "Prevent saving changes that require table re-creation".

Wednesday, December 29, 2010 6:05:53 AM UTC  #    -
SQL Server
 Monday, August 03, 2009
public int GetOrdinal(string tableName, string name)
 {
     DataView schema = GetSchemaTable().DefaultView;
     schema.RowFilter = String.Format("BaseTableName='{0}' AND ColumnName='{1}'", tableName, name);
     if (schema.Count > 0)
         return Convert.ToInt32(schema[0]["ColumnOrdinal"]);
     else
         throw new IndexOutOfRangeException();
 }
Monday, August 03, 2009 12:20:11 PM UTC  #    -
ASP NET 1.0 | ASP NET 2.0 | SQL Server
 Saturday, May 16, 2009

DECLARE @SQLString nvarchar (255),
@ParmDefinition nvarchar (255)

DECLARE @rowsCount int
DECLARE @tablename sysname, @Empty char (1)

DECLARE FindNONEmptyTables CURSOR READ_ONLY

FOR SELECT TABLE_SCHEMA+'.'+TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

OPEN FindNONEmptyTables

FETCH NEXT FROM FindNONEmptyTables INTO @tablename
WHILE (@@fetch_status = 0)
BEGIN

SET @SQLString = N'
SELECT @rowsCount= COUNT(*) FROM ' + @tablename +
'; IF EXISTS (SELECT * FROM ' + @tablename + ') set
@Empty = ''N'' ELSE set @Empty = ''Y'''
SET @ParmDefinition = N'@tablename sysname, @Empty char(1) OUTPUT, @rowsCount int OUTPUT'

EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@tablename = @tablename,
@Empty = @Empty OUTPUT,
@rowsCount = @rowsCount OUTPUT

IF @Empty = 'N'
BEGIN
 PRINT @tablename + ' rows count is :' + CAST (@rowsCount AS NVARCHAR(50))
END
FETCH NEXT FROM FindNONEmptyTables INTO @tablename
END

CLOSE FindNONEmptyTables
DEALLOCATE FindNONEmptyTables
GO

Saturday, May 16, 2009 10:19:56 AM UTC  #    -
SQL Server
SELECT CONVERT(VARCHAR(10),GETDATE(),111)
Saturday, May 16, 2009 10:18:29 AM UTC  #    -
SQL Server
 Tuesday, February 03, 2009
DateTime myDate = DateTime.MinValue; //=> 1/1/0001
SqlDateTime mySqlDate = SqlDateTime.MinValue; //=> 1/1/1753
//Note that SQL Server's smalldatetime min value is 1/1/1900
Tuesday, February 03, 2009 8:03:54 AM UTC  #    -
SQL Server
 Wednesday, January 21, 2009

if you want to shrink database log file just run this codes with your database name:

BACKUP LOG yourdbname WITH TRUNCATE_ONLY
DBCC SHRINKFILE(yourdbname_log, 2)

this code will shrink and reduce your database log file to 2MB

 

Wednesday, January 21, 2009 7:04:33 AM UTC  #    -
SQL Server
 Wednesday, November 19, 2008
SELECT TOP 1 * FROM TableName ORDER BY NEWID()
Wednesday, November 19, 2008 5:10:53 AM UTC  #    -
SQL Server
 Tuesday, November 18, 2008

Sometimes the schema of a replicated table needs altering. There are many reasons this might be the case eg possibly the datatype has been incorrectly chosen, or a default is missing, or we want to rename a column. Attempting to change the table schema directly will result in the error 

"Cannot alter/drop the table 'tablename' because it is being published for replication". 

So, how to change an existing column without breaking replication? Consider if we wanted to make the following schema change:

to

The method we choose depends in part on the replication type and size of the table, but there are 2 main options: 

(a) altering the subscriptions

  exec sp_dropsubscription   @publication =  'tTestFNames' 
     ,  @article =  'tEmployees' 
     ,  @subscriber =  'RSCOMPUTER'
     ,  @destination_db =  'testrep' 
  

  exec sp_droparticle  @publication =  'tTestFNames'
     ,  @article =  'tEmployees'
  

  alter table tEmployees alter column Forename varchar(100) null
  

  exec sp_addarticle  @publication =  'tTestFNames' 
     ,  @article =  'tEmployees' 
     ,  @source_table =  'tEmployees' 
  

  exec sp_addsubscription  @publication =  'tTestFNames'
     ,  @article =  'tEmployees'
     ,  @subscriber =  'RSCOMPUTER' 
     ,  @destination_db =  'testrep' 
  
For snapshot replication this is the obvious choice. We drop the subscription to this article, drop the article, then change the table. Afterwards the process is reversed. The next time the snapshot agent is run, it'll pick up the new schema without any issues.

For transactional replication we may choose to proceed using the script above. However, we must be more careful in this case. By default, an insert, update or delete statement performed on the publisher is propagated to the subscriber in the form of a stored procedure call. By changing the column definition, we may need to change the related stored procedures on all the subscribers. Addition of a default would be fine, but changing the datatype itself as above would require the stored procedure arguments to be modified. For the example table above, these 3 procedures exist on the subscriber in the form: 

sp_MSins_tEmployees, 
sp_MSupd_tEmployees, 
sp_MSdel_tEmployees. 

They can be generated at the publisher using sp_scriptpublicationcustomprocs but this would of course require the system to be quiesced, i.e. during this (quick) change there shouldn't be any alterations made to the publisher's data and all the subscribers should be completely synchronized. 

This is not ideal, and there is also a hidden problem here waiting to be discovered. Usually, when you add a new article to an existing publication in transactional replication, running the snapshot agent will create a snapshot of just the new article. In our case, it'll also create a snapshot of the 'tEmployees' table. So, to avoid all the issues and complications mentioned above, it's simplest to run the snapshot agent immediately after executing sp_addsubscription and then synchronize.

In merge replication, there is no possibility of dropping the subscription on a per article basis using the script above, as there is in transactional and snapshot replication. If we drop the subscription entirely including all other articles (sp_dropmergesubscription), then try to run sp_dropmergearticle there will be an error if the snapshot has already been run, so we have to set @forceinvalid_snapshot to 1, make the table change on the publisher then read the article and subscriptions and initialize which would necessitate a new snapshot generation of all articles in this publication. A nosync initialization is possible, but this can be extremely restrictive for future changes, and I'll leave that for another article.

(b) altering the table in-place

OK, in some cases the table is large and we don't want to run a new snapshot - either of the individual table (transactional) or of the whole publication (merge) - so there is an alternative method. We might use the built in stored procedures sp_repladdcolumn and sp_repldropcolumn to make the changes (note that these procedures limit the subscribers to be SQL Server 2000 only). Using these procedures we can add a dummy column to hold the data, remove the old column, add in the correct definition of the original column then transfer back the data. Now the script becomes:
  exec sp_repladdcolumn  @source_object =  'tEmployees'
     ,  @column =  'TempForename' 
     ,  @typetext =  'varchar(100) NULL' 
     ,  @publication_to_add =  'tTestFNames' 
  

  update tEmployees set TempForename = Forename
  

  exec sp_repldropcolumn  @source_object =  'tEmployees' 
     ,  @column =  'Forename' 
  

  exec sp_repladdcolumn  @source_object =  'tEmployees'
     ,  @column =  'Forename' 
     ,  @typetext =  'varchar(100) NULL' 
     ,  @publication_to_add =  'tTestFNames' 
  

  update tEmployees set Forename = TempForename
  

  exec sp_repldropcolumn  @source_object =  'tEmployees' 
     ,  @column =  'TempForename'
    
Although the above script can be used for transactional replication or merge replication, the internal methodology is different due to the differing nature of these 2 techniques. For merge replication, details of the rows updated are kept in MSmerge_contents, and if a particular row has been changed once or a hundred times, there will still only be one entry in this system table, while in transactional replication, 100 updates to a row is propagated as 100 subscriber updates. This means merge has an advantage over transactional because we need to perform 2 updates to each row to make the schema change.

 

You can find the main article in: http://www.sqlservercentral.com/articles/Replication/alteringacolumnonareplicatedtable/1666/

 

Tuesday, November 18, 2008 5:02:53 AM UTC  #    -
SQL Server
 Sunday, November 16, 2008

There are two ways :

  1. EXEC sp_dboption 'pubs', 'single user', 'TRUE'
  2. alter database pubs set SINGLE_USER  WITH ROLLBACK IMMEDIATE
To deactive single user mode :
  1. EXEC sp_dboption 'pubs', 'single user', 'FALSE'
  2. 2- alter database pubs set MULTI_USER 
Sunday, November 16, 2008 3:00:17 PM UTC  #    -
SQL Server

just run sp_who stored procedure.

Sunday, November 16, 2008 2:59:50 PM UTC  #    -
SQL Server
CREATE TABLE #TmpWho
(spid INT, ecid INT, status VARCHAR(150), 
loginame VARCHAR(150), hostname VARCHAR(150), 
blk INT, dbname VARCHAR(150), cmd VARCHAR(150))

INSERT INTO #TmpWho
EXEC       sp_who

DECLARE @spid INT     
DECLARE @getspid CURSOR     

SET @getspid = CURSOR FOR     
      SELECT       spid
      FROM      #TmpWho
      WHERE       dbname = 'YOURDBNAME'

OPEN @getspid     

FETCH NEXT FROM @getspid INTO @spid     

WHILE @@FETCH_STATUS = 0 
BEGIN
 KILL @spid --SELECT @spid works fine here
FETCH NEXT FROM @getspid INTO @spid
END
CLOSE @getspid 
DEALLOCATE @getspid 

DROP TABLE #TmpWho
Sunday, November 16, 2008 10:21:22 AM UTC  #    -
SQL Server
DECLARE @tableCatalog VARCHAR (1024) , 

@tableSchema VARCHAR (1024), @tableName VARCHAR (1024), @tableType VARCHAR (1024)
DECLARE cursorTemp CURSOR FOR
SELECT * FROM INFORMATION_SCHEMA.TABLES
OPEN cursorTemp
FETCH cursorTemp INTO @tableCatalog, @tableSchema, @tableName, @tableType


-- start the main processing loop.
WHILE @@Fetch_Status = 0
BEGIN
    EXEC (' ALTER TABLE '+@tableName+' NOCHECK CONSTRAINT ALL;' +
    ' DELETE FROM '+ @tableName +';'+
    ' ALTER TABLE '+@tableName+' CHECK CONSTRAINT ALL ') 
    FETCH cursorTemp INTO @tableCatalog, @tableSchema, @tableName, @tableType
END

CLOSE cursorTemp
DEALLOCATE cursorTemp
Sunday, November 16, 2008 10:15:16 AM UTC  #    -
SQL Server
 Wednesday, November 12, 2008
Defferent between Stored procedure and User Functions
Wednesday, November 12, 2008 6:48:11 AM UTC  #    -
SQL Server
Archive
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
Blogroll
About the author/Disclaimer

استفاده از مطالب سایت با ذکر منبع آزاد است

© Copyright 2012
Amir Mirkamali

Statistics
Total Posts: 40
This Year: 0
This Month: 0
This Week: 0
Comments: 1
Themes
All Content © 2012, Amir Mirkamali