ISNULL with SQL Server 2008 - asp.net

I want to use ISNULL with all columns of a table.
Like this
SELECT ISNULL(* , 'NA') FROM #tbl
I know its a wrong way I have to specify each column name separately to use ISNULL.
But in my case #tbl is a temporary table and columns are created dynamically
like this:
EXEC ('ALTER TABLE #tbl ADD [' + #bno + '] varchar(30)')
Due to this I can't use column names in select query because column names are always different.
So what should I do?

Change your dynamic SQL to:
EXEC ('ALTER TABLE #tbl ADD [' + #bno + '] varchar(30) NULL DEFAULT(''NA'')')

Try to get fields of your temprary table from the tempdb.sys.columns table then iterate over these:
select c.*
from tempdb.sys.columns c
inner join tempdb.sys.tables t ON c.object_id = t.object_id
where t.name like '#TableName%'

Related

How can I bulk rename table columns in a SQLite database?

I created a whole bunch of SQLite database tables. Many columns in the tables have names with spaces, which I'm now realizing was not such a brilliant idea. Is there a way to write one command which will get rid of all spaces in all columns in all tables? I know I can do it one at a time (all potential duplicates seem to address this issue rather than my issue) but it's going to take me forever. Any ideas on how I can do this?
Use the following SQL to find all of the column names that contain spaces. I also included SQL to generate a new name.
SELECT t.name as tablename, c.name as badcol, replace(c.name, ' ','_') as newcolname
FROM sqlite_master t
JOIN pragma_table_info(t.name) c
WHERE t.type = 'table' AND c.name like '% %';
From here you would have to generate alter statements looking like this:
ALTER table <tablename> RENAME COLUMN <badcol> to <newcolname>;
While I cant figure how to directly pass the list of parms to the Alter table command you can use the following SQL to generate the alter commands for you then just copy/paste the result and execute the list of them.
SELECT ('ALTER TABLE ' || t.name || ' RENAME COLUMN ' || '[' || c.name || ']'
|| ' TO ' || '[' || REPLACE(c.name, ' ','_') || '];')
FROM sqlite_master t
JOIN pragma_table_info(t.name) c
WHERE t.type = 'table' AND c.name like '% %';
In this SQL I replaced the spaces in col names with underscores but you can see where you could replace the REPLACE function with the column renaming solution you desire.

I need to display text with system generated value i.e alphanumeric value.and insert into sql database

I have 4 locations Chennai, Banglore, Hyderabad, Mumbai.
Depending on user selection from dropdown, I need to gennerate an id like this:
If they select Chennai - CHE001,CH002,CHE002,CHE003,CHE004.....etc
If they select Mumbai - MUM001,MUM002,MUM003,MUM004.......etc
If they select Hyderabad - HYD001,HYD002,HYD003,HYD004........etc
like that in database it has to save
Like that auto generated id as has to save in database but it must be in unique.... I don't how it will work with SQL functions are stored procedure, asp.net .. please kindly help for this issue.
Declare #Selected varchar(100)='Chennai'
Select Stuff((Select Distinct ',' +ID
From (Select Top 999 ID=Upper(Left(#Selected,3))+Format(Row_Number() Over (Order By (Select null)),'000') From master..spt_values ) A
For XML Path ('')),1,1,'')
Returns
CHE001,CHE002,CHE003,CHE004,CHE005,CHE006,CHE007,CHE008,CHE009,CHE010,{...},CHE997,CHE998,CHE999
Or if you need rows
Declare #Selected varchar(100)='Chennai'
Select Top 999 ID=Upper(Left(#Selected,3))+Format(Row_Number() Over (Order By (Select null)),'000') From master..spt_values
Returns
ID
CHE001
CHE002
CHE003
CHE004
CHE005
{...}
CHE997
CHE998
CHE999
You can create stored procedure similar to below:
BEGIN
DECLARE #CITY VARCHAR(MAX) = 'MUMBAI'
DECLARE #CITYCODE VARCHAR(3) = SUBSTRING(#CITY,1,3)
INSERT INTO TBL (ID)
SELECT #CITYCODE + RIGHT('000' + CAST((CAST(REPLACE(ISNULL(MAX(ID),#CITYCODE + '000'),#CITYCODE,'') AS INT) + 1) AS VARCHAR),3)
FROM TBL
WHERE ID LIKE #CITYCODE + '%'
END

Using nvarchar(MAX) to build query, but conversion fails in where clause

I have a stored procedure that uses a variable called #Command (nvarchar(MAX)). I then add parameters accordingly based on given input.
declare #Command nvarchar(max)
if(#CaseFileID IS NOT NULL)
BEGIN
select #Command='
select [ServerCredentialsID],[CaseFileID],EIKSLT.[LocationType],EPT.PaymentType,[TaskID],[DateActive]
,[LengthOfPurchase],[Username],[Password],[IPDomain],[Port],[DES],[Website],[AmountPaid],[Latitude]
,[Longitude],[HasAttachments],[TimeStamp],[CaseElement],[Temporary],[StatusID]
FROM Element17a_IKSServerCredentials EIKSSC
JOIN ElementsIKSLocationTypes EIKSLT ON EIKSSC.LocationBeingUsedID= EIKSLT.IKSLocationBeingUsedID
JOIN ElementsPaymentTypes EPT ON EIKSSC.PaymentMethodID=EPT.PaymentTypeID
where EIKSSC.CaseFileID='''+cast(#CaseFileID as nvarchar(MAX))+''' '
#CaseFileID is declared as an int, and in the table it is an int. When I try
where EIKSSC.CaseFileID = ' + #CaseFileID + ' '
then the value doesn't even show (in the error it looks like "EIKSSC.CaseFileID= '" )
I just don't get it.
NOTE: SQL Server 2008 Management Studio
It's because #CaseFileID is VARCHAR even though you don't show it.
Your IF should be
if(#CaseFileID > '')
And if even that doesn't work, then you need to swap to LEFT joins because INNER JOINs will remove records that cannot be matched in the other 2 tables.
Finally, because CaseFileID is an int, you don't need the quotes. Even though SQL Server will implicitly cast '9' to the integer 9 in the WHERE clause, it's just not necessary.
declare #Command nvarchar(max)
if(#CaseFileID > '')
BEGIN
select #Command='
select [ServerCredentialsID],[CaseFileID],EIKSLT.[LocationType],EPT.PaymentType,[TaskID],[DateActive]
,[LengthOfPurchase],[Username],[Password],[IPDomain],[Port],[DES],[Website],[AmountPaid],[Latitude]
,[Longitude],[HasAttachments],[TimeStamp],[CaseElement],[Temporary],[StatusID]
FROM Element17a_IKSServerCredentials EIKSSC
LEFT JOIN ElementsIKSLocationTypes EIKSLT ON EIKSSC.LocationBeingUsedID= EIKSLT.IKSLocationBeingUsedID
LEFT JOIN ElementsPaymentTypes EPT ON EIKSSC.PaymentMethodID=EPT.PaymentTypeID
where EIKSSC.CaseFileID='+cast(#CaseFileID as nvarchar(MAX))

Concatenating multiple rows fields into one column in T-SQL

I am writing an SQL query in which that I will need to perform a sub select on a table, which will usually return multiple rows. I need to be able to join together the results of a certain field from all the rows into one field to output. Is this possible, and how?
For example, if the SQL query returns
id | field
1 | test1
2 | test2
3 | test3
I need the outputted field to be "test1 test2 test3".
Thanks
Here's the for xml trick to do that:
SELECT field + ' ' as [text()]
FROM YourTable
FOR XML PATH ('')
This prints:
test1 test2 test3
It's typically used with an outer apply to execute it once for each row.
declare #sample table(id int, field varchar(20))
insert into #sample values(1,'test1')
insert into #sample values(2,'test2')
insert into #sample values(3,'test3')
declare #result varchar(max) set #result = ''
select #result = #result + ' '+field from #sample
select #result
A SQLCLR custom aggregator would be a an alternative (read better) solution
Try this:
SELECT RTRIM(field)
FROM (
SELECT field + ' ' field
FROM <YOUR_TABLE>
FOR XML PATH('')
) a
As an addition to the existing answers. Try including the COALESCE expression with column name your going to use. This avoids having null values in your concatenated string and avoid your list looking like this. Notice the redundant blank space.
field1 field2 field4 field
Further details can be found here.
GO
DECLARE #tableName VARCHAR(MAX)
SELECT #tableName = COALESCE(#tableName + ' ' ,'') + Name
FROM sys.tables
SELECT #tableName
GO
it is possible to do with a cursor.
declare #field nvarchar(max)
declare #concat nvarchar(max)
set #concat = ''
declare #cursor cursor
set #cursor = cursor for select field from table
open #cursor
fetch next from #cursor into #field
while ##fetch_status = 0
begin
set #concat = concat(#concat,#field)
fetch next from #cursor into #field
end
your exercise is to add space between the concatenated strings :-)

Efficient query for searching a single character from a huge table with 100 fields

I have a table that has 100 fields. The table has around 1000 records. I want to know whether any field of any record has a character "" in it. Owning to the large number of fields (100), I want to know how I can form a query to know whether any field in any record has a character "" in it. I am not supposed to be use dynamic SQL :(
OK, without using dynamic SQL you can build the static SQL you need like this:
select 'select pk, ''' || column_name
|| ''' col from mytable where '
|| column_name || ' like ''%x%'';'
from user_tab_columns
where table_name = 'MYTABLE';
That will output a select statement for each column, which you can then run as a SQL Plus script:
select pk, 'PK' col from mytable where PK like '%x%';
select pk, 'COL2' col from mytable where COL2 like '%x%';
select pk, 'COL3' col from mytable where COL3 like '%x%';

Resources