سؤال

I'm making a view to make my life easier when importing some data through C#, and it would be a huge time saver if I could do all the conversions and casting (and setting correct column lengths) on the SQL side and not in C# (because my C# code is all dynamic, not hard coded and it's falling over when stuff is not the correct length). This is more or less what I'm doing on a very small scale:

CREATE VIEW vw_pendingitems
AS
   SELECT 
      CAST(a.columnone AS CHAR(1)) 'Column 1', 
      CAST(a.columntwo AS CHAR(1)) 'Column 2', 
      CAST(a.adecimalcolumn AS VARCHAR(30)), 
      CAST(null AS VARCHAR(20)) 'A not yet defined column',
      b.anintcolumn 'An int column'
FROM table1 a
JOIN table2 b ON a.key = b.key

The first two columns are working fine, but I think I'm hitting issues when I cast a null. Are there any other/better ways of doing what I'm trying to accomplish?

هل كانت مفيدة؟

المحلول

A CAST should work fine with a nullable column. It will just return NULL. If you do not want NULL then you can use ISNULL.

SELECT ISNULL(CAST(NULL AS VARCHAR(20)), '') 'A not yet defined column'

You should be careful with changing the data types though. If you use smaller data types you could either lose data or get an error.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top