Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Monday, March 26, 2012

How disable IDENTITY on column

Hello,

I have big problem with IDENTITY column in table. I must disable this function in 500 tables in my system and i don`t know how do this :( is it such way in order to do this ?

INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel')
GO
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT dbo.Tool ON
GO

-- Try to insert an explicit ID value of 3.
INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel')
GO|||Yes I know this manner, but I can`t disable IDENTITY on all tables because system say me that I can use this function only one table in this moment and don`t allow me disable IDENTITY on tables.|||

something to start with

use northwind

select IDENTITY(int, 1,1) AS ID_Num, name AS NAME into #alltables from sysobjects where xtype='u'

BEGIN TRANSACTION
declare @.ctr int
select @.ctr=0
DECLARE @.CMD NVARCHAR(200)
while @.CTR<>(SELECT MAX(ID_NUM) FROM #alltables )
BEGIN
sELECT @.CTR=@.CTR+1
SELECT @.CMD= 'SET IDENTITY_INSERT '+NAME + ' ON' FROM #ALLTABLES WHERE
ID_NUM=@.CTR
EXEC (@.CMD)
END

ROLLBACK TRANSACTION
SELECT * FROM #ALLTABLES

rollback transaction

|||

I am not clear on what you want to do. Do you want to disable it temporarily on multiple tables? Or eliminate it permanently? I can whip up the basis of a routine to change the identity column to no longer be an identity column, but from a further reply that doesn't seem to be what you want.

You can only use SET IDENTITY_INSERT ON on only one table at a time, per connection, but this should be acceptable because you can only insert into one table at a time per connection. So if this is a temporary thing, then all you need to do is just turn it off for the table you are working on.

Expand and a better answer can possibly be arrived at.

|||I understand. :( it`s a pity that we can`t disable this function on all table on one moment... thanx for help|||

hey take a look at this

use northwind
set xact_abort off
select IDENTITY(int, 1,1) AS ID_Num, name AS NAME into #alltables from sysobjects where xtype='u'

BEGIN TRANSACTION
declare @.ctr int
select @.ctr=0
DECLARE @.CMD NVARCHAR(200)
while @.CTR<>(SELECT MAX(ID_NUM) FROM #alltables )
BEGIN
sELECT @.CTR=@.CTR+1
SELECT @.CMD= 'SET IDENTITY_INSERT '+NAME + ' ON' FROM #ALLTABLES WHERE ID_NUM=@.CTR
EXEC (@.CMD)
END

it says 33 rows affected

|||Try this:

DECLARE @.Statement nvarchar(2000)
DECLARE Statements CURSOR LOCAL FAST_FORWARD
FOR SELECT N'SET IDENTITY_INSERT ' +
QUOTENAME(TABLE_SCHEMA) +
N'.' + QUOTENAME(TABLE_NAME) + ' OFF'
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_TYPE = 'BASE TABLE' AND
OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) +
N'.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
OPEN Statements
FETCH NEXT FROM Statements INTO @.Statement
WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM Statements INTO @.Statement
BEGIN TRY
EXEC(@.Statement)
END TRY
BEGIN CATCH
SELECT 'Error:'+ERROR_MESSAGE()+' on:'+@.Statement
END CATCH
END
-- Clean up work
CLOSE Statements

If you are sure that all the tables have identity columns you can use this:

sp_msforeachtable @.command1="print '?'", @.command2="SET IDENTITY_INSERT ? OFF"

How disable IDENTITY on column

Hello,

I have big problem with IDENTITY column in table. I must disable this function in 500 tables in my system and i don`t know how do this :( is it such way in order to do this ?

INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel')
GO
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT dbo.Tool ON
GO

-- Try to insert an explicit ID value of 3.
INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel')
GO|||Yes I know this manner, but I can`t disable IDENTITY on all tables because system say me that I can use this function only one table in this moment and don`t allow me disable IDENTITY on tables.|||

something to start with

use northwind

select IDENTITY(int, 1,1) AS ID_Num, name AS NAME into #alltables from sysobjects where xtype='u'

BEGIN TRANSACTION
declare @.ctr int
select @.ctr=0
DECLARE @.CMD NVARCHAR(200)
while @.CTR<>(SELECT MAX(ID_NUM) FROM #alltables )
BEGIN
sELECT @.CTR=@.CTR+1
SELECT @.CMD= 'SET IDENTITY_INSERT '+NAME + ' ON' FROM #ALLTABLES WHERE
ID_NUM=@.CTR
EXEC (@.CMD)
END

ROLLBACK TRANSACTION
SELECT * FROM #ALLTABLES

rollback transaction

|||

I am not clear on what you want to do. Do you want to disable it temporarily on multiple tables? Or eliminate it permanently? I can whip up the basis of a routine to change the identity column to no longer be an identity column, but from a further reply that doesn't seem to be what you want.

You can only use SET IDENTITY_INSERT ON on only one table at a time, per connection, but this should be acceptable because you can only insert into one table at a time per connection. So if this is a temporary thing, then all you need to do is just turn it off for the table you are working on.

Expand and a better answer can possibly be arrived at.

|||I understand. :( it`s a pity that we can`t disable this function on all table on one moment... thanx for help|||

hey take a look at this

use northwind
set xact_abort off
select IDENTITY(int, 1,1) AS ID_Num, name AS NAME into #alltables from sysobjects where xtype='u'

BEGIN TRANSACTION
declare @.ctr int
select @.ctr=0
DECLARE @.CMD NVARCHAR(200)
while @.CTR<>(SELECT MAX(ID_NUM) FROM #alltables )
BEGIN
sELECT @.CTR=@.CTR+1
SELECT @.CMD= 'SET IDENTITY_INSERT '+NAME + ' ON' FROM #ALLTABLES WHERE ID_NUM=@.CTR
EXEC (@.CMD)
END

it says 33 rows affected

|||Try this:

DECLARE @.Statement nvarchar(2000)
DECLARE Statements CURSOR LOCAL FAST_FORWARD
FOR SELECT N'SET IDENTITY_INSERT ' +
QUOTENAME(TABLE_SCHEMA) +
N'.' + QUOTENAME(TABLE_NAME) + ' OFF'
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_TYPE = 'BASE TABLE' AND
OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) +
N'.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
OPEN Statements
FETCH NEXT FROM Statements INTO @.Statement
WHILE @.@.FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM Statements INTO @.Statement
BEGIN TRY
EXEC(@.Statement)
END TRY
BEGIN CATCH
SELECT 'Error:'+ERROR_MESSAGE()+' on:'+@.Statement
END CATCH
END
-- Clean up work
CLOSE Statements

If you are sure that all the tables have identity columns you can use this:

sp_msforeachtable @.command1="print '?'", @.command2="SET IDENTITY_INSERT ? OFF"sql

Friday, March 23, 2012

How could I obtain the domain name from SQL?

Dear fellows,
I would need from T-SQL job or through any friendly-user function (VB
front-end app) the aforementioned value.
With EXEC xp_cmdshell 'IPCONFIG /ALL' I get values such as HOST NAME or
IP Adress. Problem is the following: if oneself launch IPCONFIG /ALL from a
DOS session it is obtained DNS suffixes list with values hoped: domain,
Active Directory and so on. But launched from Query Analyzer due to it
returns more than a row appear as NULL value.
Does anyone know how/where it is available?
Best regards,> But launched from Query Analyzer due to it
> returns more than a row appear as NULL value.
Is this the only problem?
CREATE TABLE #foo(cmd VARCHAR(1024))
INSERT #foo EXEC master..xp_cmdshell 'IPCONFIG /ALL'
SELECT * FROM #foo WHERE cmd IS NOT NULL
DROP TABLE #foo|||Dear Aaron,
Is this the only problem?
No!
Your solution not works because of appers the line empty.
Thanks a lot for your support,
"Aaron Bertrand [SQL Server MVP]" wrote:

> Is this the only problem?
>
> CREATE TABLE #foo(cmd VARCHAR(1024))
> INSERT #foo EXEC master..xp_cmdshell 'IPCONFIG /ALL'
> SELECT * FROM #foo WHERE cmd IS NOT NULL
> DROP TABLE #foo
>
>|||> Your solution not works because of appers the line empty.
Okay, so is this really that difficult?
SELECT * FROM #foo WHERE cmd > ''

Monday, March 12, 2012

How can we call Function into Select qry ?

Hi ,
I need to call Function in Select Qry and some of the field of that Qry is
Input to
Function
like select Col1,col2, (select dbo.fn(Col1))Col3 from X
Any help Please ?
KrisKris wrote:
> Hi ,
> I need to call Function in Select Qry and some of the field of that
> Qry is Input to
> Function
> like select Col1,col2, (select dbo.fn(Col1))Col3 from X
> Any help Please ?
> Kris
Select
Col1, Col2, dbo.fn(Col1), Col3
From
X
Is that what you mean? If not, maybe what you're talking about is the
APPLY operator in SQL 2005 which allows you to add columns to a result
set based on the results of a function:
Select Col1, Col2
CROSS APPLY dbo.MyFunc(Col1)
David Gugick - SQL Server MVP
Quest Software|||David Thanks for your reply.
What I understand is, We can not use function into Select Qry, as function
suppose to return value for each records. I have to use Cursor.
Declare c1 -->select IdNum,(COl1+Col2)Col3 from X
read Value into @.Variable
select dbo.fn(@.Variable)
When I used Function in Select Qry. It is not returning value for all record
s,
select col1,col2, (select dbo.fn(col1+col2)) Col3 from X return Values
something like
Col1, Col2 ,Col3
A B AB
X Y AB
Is there any other way i can call fuction in select Qry becoz cursor is slow
.
Thx-Kris
"David Gugick" wrote:

> Kris wrote:
> Select
> Col1, Col2, dbo.fn(Col1), Col3
> From
> X
> Is that what you mean? If not, maybe what you're talking about is the
> APPLY operator in SQL 2005 which allows you to add columns to a result
> set based on the results of a function:
> Select Col1, Col2
> CROSS APPLY dbo.MyFunc(Col1)
>
> --
> David Gugick - SQL Server MVP
> Quest Software
>|||Kris (Kris@.discussions.microsoft.com) writes:
> David Thanks for your reply.
> What I understand is, We can not use function into Select Qry, as function
> suppose to return value for each records. I have to use Cursor.
> Declare c1 -->select IdNum,(COl1+Col2)Col3 from X
> read Value into @.Variable
> select dbo.fn(@.Variable)
> When I used Function in Select Qry. It is not returning value for all
> records,
> select col1,col2, (select dbo.fn(col1+col2)) Col3 from X return Values
> something like
> Col1, Col2 ,Col3
> A B AB
> X Y AB
> Is there any other way i can call fuction in select Qry becoz cursor is
> slow.
It's not fully clear what sort of function you have, but it seems like
you have a scalar function. In such case you can do:
SELECT col1, col2, dbo.fn(col1 + col2) AS Col3 FROM X
If you don't get back all rows as expected, you may have some other
problem with your actual query.
If you have a table-valued function, it depends on which version of
SQL whether you can do this in query or not.
It is difficult to assist when you don't give accurate information of
what you are doing. Could you include the actual code you are using?
Also, please specify which version of SQL Server you are using.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Wednesday, March 7, 2012

How can import mdf file to mssql 2005

Dear All,

I have a mdf file and want to import the file to mssql 2005, But i can't find the function when i right click the database name in SQL Server Management Studio. What should i do?

Regards,

Ricky

You can choose to attach the mdf file as a new database. Right-click on the 'Databases' option on SSMS and click attach or use T-SQL (sp_attach_db).|||

hi

Gargi is very right,

I would like to Add,

the thing is you need to attached the .mdf file as well as its log file with that mdf file.

(this is the process of attaching, there is no direct process of importing a mdf file)

Regrds,

Thanks.

Gurpreet S. Gill

|||I just want to add once you attach a 2000 database in 2005 you can't go back just make sure you have a copy.

How can import mdf file to mssql 2005

Dear All,

I have a mdf file and want to import the file to mssql 2005, But i can't find the function when i right click the database name in SQL Server Management Studio. What should i do?

Regards,

Ricky

You can choose to attach the mdf file as a new database. Right-click on the 'Databases' option on SSMS and click attach or use T-SQL (sp_attach_db).|||

hi

Gargi is very right,

I would like to Add,

the thing is you need to attached the .mdf file as well as its log file with that mdf file.

(this is the process of attaching, there is no direct process of importing a mdf file)

Regrds,

Thanks.

Gurpreet S. Gill

|||I just want to add once you attach a 2000 database in 2005 you can't go back just make sure you have a copy.

How can I use SqlDataSource to read a row?

The new databound controls are great, but somehow doing the simpler things has gotten harder.The code is in a function that is passed pollid. I want to use SqlDataSource to get the smallest value of answerid where pollid = the value passed for pollid. For example:

"Select top from PollAsnwers where pollid=" & PollId & " order by AnswerId"

I can set up the SqlDataSource for a data reader to fill a GridView control, but that isn't what I want to do. In fact, I can't find anything on SqlDataSource that doesn't also involve the GridView control.

I have so far:

Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim myReader As SqlDataReader

myConnection = New SqlConnection()
myConnection.ConnectionString = ConfigurationManager.ConnectionStrings("UserPolls").ConnectionString

myCommand = New SqlCommand()
myCommand.CommandText = "Select top from PollAsnwers where pollid=" & PollId & " order by AnswerId"
myCommand.CommandType = CommandType.Text
myCommand.Connection = myConnection
myCommand.Connection.Open()

Now assuming I have a single row of data, how do I read the value of Answerid? If I have this wrong, what should I have?

Diane

select top 1 AnswerId from..... order by AnswerId.

|||

Already did that - it's in the example I posted. What I don't know is how to read the data from the record. In classic ASP, if I had a recordset called rs, I would do:

Dim newId as integer

newId = rd("AnswerId")

How do I do this with a SqlDataSource?

Diane


|||

I found an article that helped. A less than perfect but working solution is:

Dim userpoll As New UserPolls
SqlDataSource1.SelectCommand = "Select Top 1 [PollId], [AnswerId] from [PollAnswers] where pollid=" & PollId & " order by AnswerId"
Dim dv As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
For Each dr As DataRow In dv.Table.Rows
AnswerId = dr("AnswerID")
Next

The For..Next is not needed, but since I'm only returning one record, it won't hurt.

|||

Just a quick addition to what yo already have: you should be using Parameterized Queries. Do a search for it in these forums and you will find how/why to use parameterized queries. In brief, to avoid SQL Injection attacks.

|||

A search turned up three results - your post here, another post by you and one more that also recommends using parameterized quieries. Can you direct me to a tutorial or article?

Diane

|||

Sure: Here's a few:

http://aspnet101.com/aspnet101/tutorials.aspx?id=1

http://dotnetjunkies.com/WebLog/dinakar/articles/74220.aspx

http://davidhayden.com/blog/dave/archive/2005/10/24/2528.aspx

If you are wondering how/where I got them ... Goooooooglee.....Smile

Friday, February 24, 2012

How can i use default schemas of users in a function ?

Hi,

I've a Problem with a Function called by different users.

I want the different callers to query a table in their own default Schema.

So if i refence the full Path [Schema].[Tablename] it works Properly.

If i just Use the [Tablename] for reference it fails.

The function was created with EXECUTE AS CALLER option ;

if I call it with dynamic SQL i retreive the error-message

"Only functions and extended stored procedures can be executed from within a function."

does anybody know a solution for this problem?

thanks in advance

Raimund

Raimund wrote:

So if i refence the full Path [Schema].[Tablename] it works Properly.

If i just Use the [Tablename] for reference it fails.

The function was created with EXECUTE AS CALLER option ;

I quote from Books Online (search for "Object Visibility and Qualification Rules")

"

USE DBY SELECT * FROM DBY..TableX

Because LoginX is associated with UserA in DBY, SQL Server first looks for DBY.UserA.TableX. If there is no table with this name, SQL Server looks for a table DBY.dbo.TableX. "

So engine look for [yourCallerUser].[Tablename] and for [dbo].[Tablename] and find no [Tablename]

Then I think you have to maintain full path [Schema].[Tablename] to objects reference.

|||

Hm,

so i guess i have to path the query-results by parameter to the function.

It looks horrible but it works.

Best Regards

Raimund

How can I Use a User Defined function as a default for a column value?

Hi, I have an int column for which I want to set to a certain code value, e.g.: In my table "Biometric" I have a column called "BiometricStatusCode" which is a foreign key to a Table/Column "REF_PERSON_BiometricStatusCodes:BiometricStatusID"

In that REF_PERSON_BiometricStatusCodes table, I have a row of data that returns a value of "All Others", the PK id for this row happens to be 3.

I can enter 3 as my default for the column in my original "Biometric" table...that will work fine and return "All Others" when joined...as long as the PK for "All Others" is 3. However, I cannot guarantee that in customer installations, hence I want to use a function that returns the Int/PK code for the row of data that contains "All Others" in my REF_PERSON_BiometricStatusCodes table.

So..........I created this function:

Create FUNCTION [dbo].[ufn_SelectDefaultBiometricStatusCode]()

RETURNS int

AS

BEGIN

DECLARE @.ret int;

SELECT @.ret = [BiometricStatusID]

FROM [AFR].[dbo].[REF_PERSON_BiometricStatusCodes] where

Upper([BiometricStatusDescr]) = 'ALL OTHERS';

IF (@.ret IS NULL)

SET @.ret = 0

RETURN @.ret

END;

The function works fine, it's not full proof...but is ok.

When I enter the function name, no quotes in the "Default Value or Binding" property in the table designer in sql 2005, it returns an error: "error validating the default for column".

The column is an int, the function returns an int... I can't figure it out..

Anyone have any ideas?

thanks.

You can use a computed column.

If you use SQL Server Management Studio to modify the table - use the column properties tab - Computed Column Specification - Formula.